I have a C program and i have created a DLL file. I am using Windows Vista, and Visual C++.
Now I need to access a method from that DLL, from the Main() method of a
See using a class defined in a c++ dll in c# code which has a great accepted answer. And as Hans Passant wrote in the comments, you cannot add a native DLL as a reference to a C# project.
When I refer to one of my own native DLLs, I usually either add a dependency between the C# project and the project which generates the native DLL, or I add the DLL as a linked content file in the C# project, like so:
This will copy the DLL to the bin\Debug
folder of the C# project and make sure that, if you once decide to create a Setup project, you can easily reference all content files and include them in the Microsoft Installer package.
Now, to be able to see the functions written in your native DLL, you have to take care of exporting them (see Exporting C Functions for Use in C or C++ Language Executables and Exporting from a DLL Using __declspec(dllexport)). So you'd have to add an extern "C"
block around your function declaration (I am assuming you wrote your code in a .cpp source file and this means that the compiler will emit mangled function names if you do not declare them as being extern "C"
):
extern "C"
{
__declspec (dllexport) void __cdecl Foo(const char* arg1);
}
...
void Foo(const char* arg1)
{
printf ("Hello %s !", arg1);
}
The __declspec (dllexport)
decoration means that the compiler/linker will have to make the function visible from outside of the DLL. And the __cdecl
defines how parameters will be passed to the function (the standard "C" way of doing this).
In your C# code, you'll have to refer to your DLL's exported methods:
class Program
{
[DllImport("mydll.dll")]
internal static extern void Foo(string arg1);
static void Main()
{
Program.Foo ("Pierre");
}
}
You should read the Platform Invoke Tutorial which gives all the gory details.