简体   繁体   中英

How do you make a method avaible to other dlls in a c++ dll in managed code?

The first piece of code is the example i am working on, after changing it to the second example, it works exept for the __declspec(dllexport) wich gives a __declspec(dllexport) cannot be applied to a function with the __clrcall calling convention. removing that piece of code does make the dll compile but the method is unavaible to the target dll. Also when i use PE Explorer to look into the DLL there are no export methods. Is there a managed variant for the __declspec(dllexport)?

extern "C" __declspec(dllexport) int UserInstruction (HWND hWnd,
                              HINSTANCE hInst,
                              double FAR *Function, 
                              char FAR *Str1,
                              char FAR *Str2)
{
       strcpy(Str1, "TEST FUNCTION");
       return (TRUE);
}


extern "C" __declspec(dllexport) int UserInstruction (IntPtr hWnd, IntPtr hInst, double *Function, char *Str1, char *Str2)
{
    Str1 = "TEST FUNCTION";
    return (true);
}

The C++/CLI compiler does support exporting managed functions. It automatically generates a thunk that loads and initializes the CLR if necessary so that the managed code can be executed. Beware the overhead. You however can't use any managed types for the function arguments. IntPtr in your case. That doesn't make sense, the unmanaged code that calls your function won't be using managed types.

You'll have to marshal them yourself. Not a problem here, these are pointers so you can simply cast to IntPtr:

extern "C" __declspec(dllexport) 
int __stdcall UserInstruction (HWND hWnd, HINSTANCE hInst, double FAR *Function, char FAR *Str1, char FAR *Str2)
{
    IntPtr windowPtr = (IntPtr)hWnd;
    IntPtr instancePtr = (IntPtr)hInst;
    // etc..
}

Explicitly selecting the calling convention is always a good idea. I added __stdcall for that reason, the most common one for exported DLL functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM