问题
I'm pretty new in C#. I have Dll written on C++ by myself and I'm going to use functions from that dll in C# app.
So, I do the following when declare functions in C++ project:
public static __declspec(dllexport) int captureCamera(int& captureId);
Then I'm trying to import this method in C# app:
[DllImport("MyLib.dll")]
public static extern int captureCamera(ref int captureId);
But I have the exception:
Unable to find an entry point named 'captureCamera' in DLL 'MyLib.dll'.
The task is to do dllimport without specifying EntryPoint parameter. Could anyone help me?
回答1:
You are defining a C++ function without an extern "C" block. As C++ allows you to overload functions (i.e. create many captureCamera() functions with different sets of arguments), the actual function name inside the DLL will be different. You can check it by opening Visual Studio Command prompt, going to your binary directory and running this:
dumpbin /exports YourDll.dll
You will get something like this:
Dump of file debug\dll1.dll
File Type: DLL
Section contains the following exports for dll1.dll
00000000 characteristics
4FE8581B time date stamp Mon Jun 25 14:22:51 2012
0.00 version
1 ordinal base
1 number of functions
1 number of names
ordinal hint RVA name
1 0 00011087 ?captureCamera@@YAHAAH@Z = @ILT+130(?captureCamera@@YAHAAH@Z)
Summary
1000 .data
1000 .idata
2000 .rdata
1000 .reloc
1000 .rsrc
4000 .text
10000 .textbss
The ?captureCamera@@YAHAAH@Z is the mangled name that actually encodes the arguments you've specified.
As mentioned in other answers, simply add extern "C" to your declaration:
extern "C" __declspec(dllexport) int captureCamera(int& captureId)
{
...
}
You can recheck that the name is correct by rerunning dumpbin:
Dump of file debug\dll1.dll
File Type: DLL
Section contains the following exports for dll1.dll
00000000 characteristics
4FE858FC time date stamp Mon Jun 25 14:26:36 2012
0.00 version
1 ordinal base
1 number of functions
1 number of names
ordinal hint RVA name
1 0 000110B4 captureCamera = @ILT+175(_captureCamera)
Summary
1000 .data
1000 .idata
2000 .rdata
1000 .reloc
1000 .rsrc
4000 .text
10000 .textbss
回答2:
public static __declspec(dllexport) int captureCamera(int& captureId);
is that method? If it is function, it cannot be static, as static
and dllexport
are mutually exclusive.
And the name is mangled. See http://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B_Name_Mangling. If you can get the mangled name, and then provide the DllImport
with it (EntryPoint=MANGLED_NAME
), it should work.
You can provide linker with .def
file, containing definition of exported functions, and their names aren't mangled then:
Project.def:
EXPORTS
captureCamera @1
回答3:
Are you declaring
extern "C" {
__declspec(dllexport) int captureCamera(int& captureId);
}
inside your c++ code - C# can only access C, not C++ functions.
来源:https://stackoverflow.com/questions/11188830/c-sharp-dllimport-library-written-on-c