1

In C# the extern modifier is used to declare a method that is implemented externally. Usually it is used with DllImport attribute to call some function in unmanaged code.

I wonder if there is a way to provide custom implementation of extern method?

To understand better the problem consider the following use case. I have a set of functions implemented in unmanaged code and I'd like to supply pointers to these function in run-time (during the loading of assembly).

The same thing DllImport attribute does, but I'd like to provide pointers by myself.

Vitali
  • 11
  • 1
  • There's no mechanism beyond [DllImport] that I know of that allows binding an *extern* method to code elsewhere. Maybe a .netmodule but they are hard to deal with. – Hans Passant Aug 30 '11 at 16:09

2 Answers2

1

This is possible although you would need to PInvoke several things (LoadLibrary and GetProcAddress - see links below)... it is called "late binding native code"...

Some relevant links with source:

Yahia
  • 69,653
  • 9
  • 115
  • 144
  • If you combine that with GetProcAdress it does... and if you follow the links you will see that the source code there provides even more flexible means than that... – Yahia Aug 30 '11 at 15:24
  • These links are very helpful. In fact, currently I am using approach with `Marshal.GetDelegateForFunctionPointer`. But this approach is too slow. It twice slower than calling unmanaged function with `DllImport` attribute. – Vitali Aug 30 '11 at 15:40
  • 1
    @Vitaly why is the performance of that relevant? You only need to call GetDelegate... once and then you can cache the result. Calling the delegate should be fast. – CodesInChaos Aug 30 '11 at 15:52
  • The reason I ask this question is that for some functions just call to unmanaged functions takes more time than its implementation. So I try to resolve this issue. I'd like to have (if possible) an approach as fast as with `DllImport` attribute. – Vitali Aug 30 '11 at 16:04
  • This approach allows for loading the implementation dynamically - so you can load for the same external function a different implemenation at runtime (for example configurable)... you could deliver different implementations in different DLL files, the user could even choose which implementation to use, and won't need to change your code to execute any of them... never compared performance though with `DllImport`... – Yahia Aug 30 '11 at 16:40
0

You would need to use LoadLibrary and GetProcAddress

CommonSense
  • 341
  • 1
  • 6