views:

389

answers:

2

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  A: 

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.

tommieb75
Does it have to be in the bin\debug directory? It's an unmanaged DLL, so anywhere in the normal PATH search ought to work, right?
Nick
Also if it is a char* it takes make sure you add the `CharSet = CharSet.Ansi` to the DllImport attribute to ensure the string is marshalled as a multibyte charactrer string
tyranid
@Nick: for the sake of not cluttering up the Windows folder with developer built DLLs, it would be preferable to deploy that DLL in the same directory where the .NET exe program resides in. The project directory corresponds to the project in the Solutions Window in Visual Studio. For example, a Solution called SolnFoo has a project called Foo, then there will be a Foo\bin\debug folder where the .NET exe got built.
tommieb75
@tommieb75 - I agree it would be *preferable*... but it is not *required* which is what was implied in your answer.
Nick
@Nick: Fair enough, of course sure, if it's located in the PATH then that's no problem... :)
tommieb75
A: 

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.

Sameh Serag