Native/Mixed-mode dll linking error in vs2010
I am trying to understand how native code can interact with .NET code and am basically trying to implement the example in the answer to this topic. The example code has two parts, one that goes into a .dll compiled with the /clr option:
__declspec(dllexport) bool toUpper(void)
{
return true;
}
and the code that is supposed to call this function goes into a win32 application, which is compiled natively:
bool toUpper(void);
int _tmain(int argc, _TCHAR* argv[])
{
bool b = toUpper();
return 0;
}
However vs2010 gives the following linker error:
error LNK2019: unresolved external symbol "bool __cdecl toUpper(void)" (?toUpper@@YA_NXZ) referenced in function _wmain
As soon as I turn off the /clr option on the dll project, everything works, so I assume that I have all the dependencies between the projects set up correctly. Any suggestions on w开发者_JS百科hat I did wrong?
You must have used Project + Project Dependencies to get this to work without /clr. Yes, this doesn't work if the project is compiled with /clr. Using a .lib for managed code is quite unusual. You have to explicitly tell the linker to link the .lib of your managed project.
Right-click the EXE project, Properties, Linker, Input, Additional Dependencies setting. Assuming both projects are in one solution, enter this:
..\$(ConfigurationName)\mumble.lib
Where mumble is the name of your managed project. Repeat for the Release configuration.
Beware that using managed code this way does not scale well. The C++/CLI compiler automatically generates a thunk for the exported function that makes sure that the CLR is loaded and initialized before calling the managed function. That however does come at a cost, I clocked it at 640 nanoseconds per call on my laptop, not counting the overhead of initializing the CLR. Using COM is an effective way to avoid that cost. Or you can host the CLR yourself, look up CorBindToRuntimeEx().
精彩评论