Home > Software engineering >  P/Invoke (DLLImport) Different Function Signature
P/Invoke (DLLImport) Different Function Signature

Time:07-28

According to the documentation, when trying to call unmanaged code in my managed code, it should has the exact same function signature as the unmanaged code.

I tried putting in a different function signature that I know should not have worked.

Original:

int Foo(LibraryDefinedString str, _Outptr_ LibraryDefinedHandle * ptr)

Adaptation (after calling DllImport):

Uint32 Foo(byte[] str, IntPtr ptr)

No exceptions were thrown. Even after I changed the parameters (putting floats or another user-defined type), it still did not throw any exception.

Have not tested whether the function in the Dll actually gets called, but my main question : Is there no warning or error when putting different function signatures from the unmanaged code?

CodePudding user response:

No, there is no warning. How could there be? There is no reflection on the native side, so there is no way for the PInvoke marshaller to validate if the managed side is correct. Either the code works, or the code has undefined behavior that may or may not fail.

In any case, your "wrong signature" may or may not be wrong. int and UInt32 have the same size. LibraryDefinedHandle* and IntPtr have the same size. What we don't know is what LibraryDefinedString is actually defined as and whether byte[] is compatible with it or not.

If the signature is mismatched, there are no errors reported on the managed side, but you may get crashes or wrong behavior on the native side.

  • Related