I have a DLL which exports a C++ function that I want to call. I’ve attempted to use DllImportAttribute and LoadLibrary/GetProcAddress but I’m stuck with both.
This is an example DLL I want to use
class Test {
__declspec(dllexport) static LPCWSTR DoSomeThingUseful(const LPCWSTR param) {
return L"Hello Dll";
}
};
The program compiles but I get an error “Entry Point Not Found - The procedure entry point for ?DoSomethingUseful could not be located in the dynamic link library …”
My second attempt using LoadLibrary and GetProcAddress
import rtl
let mod: HMODULE = LoadLibrary("Dll1.dll")!
let proc = GetProcAddress(mod, "?DoSomeThingUseful@Test@@CAPB_WPAPB_W@Z") as! (LPCWSTR) -> LPCWSTR
proc("123")
This doesn’t compile because casting fails - "Cannot cast from “FARPROC” to “Func<LPCWSTR!,LPWSTR!>!”
The name is correct. I can call the function using this C++ code
typedef LPCWSTR(__cdecl *myFunc)(LPCWSTR);
int main()
{
auto m = LoadLibrary(L"Dll1.dll");
auto p = reinterpret_cast<myFunc>(GetProcAddress(m, "?DoSomeThingUseful@Test@@CAPB_WPB_W@Z"));
wprintf(p(L"123"));
return 0;
}
The \x01 is used to disable escaping which is required for c++ mangling. Do note that if you use global members with extern “C” { } it will not do any mangling and there’s no need for \x01.
Wouldn’t it be far more reasonable that if @SymbolName and @CallingConvention determine decorated names when using DllExport they would also determine names when using DllImport?
First of all, it sucks that I have to export the function with an underscore because when importing it the underscore gets added on its own…
Second, is that I can’t simply ad to both the caller and the callee the following line
@CallingConvention(CallingConvention.Stdcall)
Unfortunately that would change how the function is exported (it would become _Foo@0), but the importing side would continue to look for _Foo, which results in:
If I change the arguments I need to mess with the name decorations again.
And additional nicety might be if importing would work with @SymbolName instead of only with the EntryPoint property of the @DllImport attribute, but that’s far less important than supporting name decoration in the toolchain rather than forcing the user to deal with it.