5

Is it possible to call a function in a C++ DLL from C code? The function is not declared extern "C". An ugly platform dependent hack that only works with Visual Studio is fine.

Calling conventions should not be a major issue, but how do I deal with name mangling.? For instance with Visual Studio, a C++ function with signature void f() has the mangled name ?f@@YAXXZ and that is not a legal C identifier.

(You don't need to tell me that I should declare the C++ function as extern "C". I already know that. But I'm in a situation where I cannot change the C++ code.)

Johan Råde
  • 20,480
  • 21
  • 73
  • 110

5 Answers5

8

Wrap the offenging function in another C++ function, and declare it with extern "C". No need to create a special DLL for it, just include one C++ file in your project.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • While using GetProcAddress works, this is the correct solution. It is portable, and will adapt to changes in the calling convention of the DLL (in case the creator ever changes it). It also doesn't rely on hard coded hand-mangled names. Please do it this way. – Speed8ump Jan 05 '14 at 03:41
4

To make your compiler to statically link a function with a different exported name may be tricky. But you can always load the DLL with LoadLibrary and then use GetProcAddress.

nullptr
  • 11,008
  • 1
  • 23
  • 18
2

You could investigate

LoadLibrary("path to dll");

to load the DLL and

GetProcAddress("?f@@YAXXZ");

to grab a function pointer to the externally declared function.

Jimmy
  • 6,001
  • 1
  • 22
  • 21
1

I do not see any clean solution besides creating an additional dll written in C++ and exposing all interfaces via extern "C".

0

You could compile your C code using the same C++ compiler they used, then your C functions will be mangled using the same mechanism and everything will link seamlessly, and no-one will notice any difference.

If you must use a different compiler, then you'll have to manually load the dll using LoadLibrary and each function using GetProcAddress.

gbjbaanb
  • 51,617
  • 12
  • 104
  • 148
  • 1
    I have to compile my C code using the Visual Studio C compiler, and it does not mangle names the same way as the Visual Studio C++ compiler. – Johan Råde Jan 04 '14 at 13:27
  • @user763305 there's still a VS C compiler?! I thought they just used the same one for all C and C++ code nowadays with a different flag (compile as C or C++ code [/Tc or /Tp](http://msdn.microsoft.com/en-us/library/032xwy55.aspx)) – gbjbaanb Jan 04 '14 at 13:35
  • You might be right, but anyway I need to compile with /Tc and the name mangling is different with /Tc and /Tp. – Johan Råde Jan 04 '14 at 14:03