0

I am trying to use a C++Builder 11.1.5 created DLL in MSVC 2022 C++ project. Both are 32bit. I can't build the DLL in MSVC as it uses some VCL objects.

My C++ Builder defines the external function thus:

extern "C" __declspec(dllexport) void __stdcall SetEnabled(bool val) {
    ...
}

MSVC uses a header to reference the function:

extern "C" __declspec(dllimport) void __stdcall SetEnabled(bool val) ;

I have created a .DEF file with the same name as the DLL, containing this:

LIBRARY MYTESTDLL
EXPORTS
 SetEnabled 

And I have generated a .LIB file from this .DEF file using MS lib.exe:

lib.exe /DEF:MYTESTDLL.def /out:MYTESTDLL.lib /MACHINE:x86

Finally, I have added MYTESTDLL.lib to my MSVC project in the Linker->Additional Dependencies section.

But, when I build the program, I get this error:

Error LNK2019 unresolved external symbol __imp__SetEnabled@4 referenced in function _WinMain@16

I've tried adding the ordinal (@4) to my .DEF file and rebuilding the .LIB file, but I still get the same error.

In a hex editor, I can that __imp__SetEnabled is in the .LIB file, but clearly not in a way that MSVC likes.

Have I missed a step somewhere? Is there anything obviously wrong with what I've done?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
AndyB
  • 162
  • 8
  • not sure if still true but older C++Builders use different mangling than MSVC++ ... try to use any DLL inspection tool to see the real names inside DLL ... if nothing works use [dynamic DLL function loading](https://stackoverflow.com/a/18030748/2521214) ... – Spektre Aug 05 '22 at 13:26

1 Answers1

0

Changing the MSVC header used to reference the function to:

extern "C" __declspec(dllimport) void SetEnabled(bool val) ;

and adjusting the C++Builder DLL to export the functions using __cdecl resolved the issue. I didn't realize that the __stdcall exported functions need decorating in .DEF file.

That said, I find that the DLL is fine unless I try to execute code in it that uses the VCL. Then things don't work properly. I wonder if it's not possible to write a DLL in C++Builder containing VCL code for use in MSVC?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
AndyB
  • 162
  • 8
  • "dont work properly" - what does this mean? Have you statically linked in all the vcl into your dll ? (project options static link for packages and run time) – Roger Cigol Aug 05 '22 at 10:18
  • It is not a problem to use `__stdcall` (you should), you just need to make sure the `.DEF` file references the correct exported name. You can use Borland's `TDUMP` or MSVC's `DUMPBIN` tool to get that name from the DLL. – Remy Lebeau Aug 05 '22 at 20:31