DllImport Unmanaged, Non .NET Dll to .NET Project

2020-04-16 02:19发布

问题:

I have a DLL non .net and unmanaged written in Borland C++ that I need to import. It returns void and has the identifier __stdcall on the function. It also requires passing of char *. When I try to add it as a reference to my project in VS 2005, it returns an error of not valid assembly.

How can I do this in C#?

This what I currently have and it does not work:

[DllImport ("Project1.dll", CallingConvention=CallingConvention.StdCall)]
    public static extern IntPtr CustomerForm
        (String caption);

回答1:

For an unmanaged DLL you do not add it as a reference. Make sure the binary DLL is located in the same folder as the build where the .NET EXE project resides in usually {project}\bin\debug.

Also, make sure that you had a .DEF file for the exports when you built the unmanaged DLL with Borland C++.

Edit:

LIBRARY Project1
EXPORTS
    CustomerForm

And in your Borland C++ source make sure that the function is declared as export, for an example:

#ifdef __cplusplus
__declspec(dllexport) void CustomerForm(char *s);
#endif

Using this will ensure that the function is exportable and can be linked!

Make sure the signature of your DllImport attribute matches up to the signature of your native C++ Dll i.e.

[DllImport ("Project1.dll", CallingConvention=CallingConvention.StdCall)]
    public static extern void CustomerForm(string caption);

Hope this helps, Best regards, Tom.



回答2:

To use DllImport, you don't need to add a reference of the dll, just put the dll beside your executable or in system32 and it should work.