Access a method from a DLL from C# program -
i have c program , have created dll file. using windows vista, , visual c++.
now need access method dll, main() method of c# code. steps of doing so?
so far have added dll file reference, thereafter should do?
this example:
int main1( void ) { prinf("hello world"); }
please note class makes of other .lib functions, able create dll out of it. (i don't know if relevant)
now need access method c# main();
[stathread] static void main() { // need call main1() method here application.enablevisualstyles(); application.setcompatibletextrenderingdefault(false); application.run(new form1()); }
see using class defined in c++ dll in c# code has great accepted answer. , hans passant wrote in comments, cannot add native dll reference c# project.
when refer 1 of own native dlls, either add dependency between c# project , project generates native dll, or add dll linked content file in c# project, so:
- right-click on project , choose add > existing item.
- browse , select dll want, don't click add yet.
- click on tiny arrow @ right of add button , select add link.
- select dll appears in c# project , go properties.
- make sure have build action set content.
this copy dll bin\debug
folder of c# project , make sure that, if once decide create setup project, can reference content files , include them in microsoft installer package.
now, able see functions written in native dll, have take care of exporting them (see exporting c functions use in c or c++ language executables , exporting dll using __declspec(dllexport)). you'd have add extern "c"
block around function declaration (i assuming wrote code in .cpp source file , means compiler emit mangled function names if not declare them 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 compiler/linker have make function visible outside of dll. , __cdecl
defines how parameters passed function (the standard "c" way of doing this).
in c# code, you'll have refer 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 platform invoke tutorial gives gory details.
Comments
Post a Comment