What would be a common strategy for using DLLs coded in native C++ in C#? I'm not really finding much good information about it, other than writing the DLL in C.

7 Years
Discussion Span
Last Post by mike_2000_17

DLLs written in C++ can not be used by non-c++ languages unless you make the functions look like C functions by adding extern "C" to them, which prevents the compiler from mangling function names. In otherwords you will have to write C wrapper functions around the c++ code in the DLL.


AD is right, because of name-mangling in C++ (and ABI), you have to wrap all your C++ code into a C API (C functions). For example, say I wanted to "export" the following class from a DLL:

class Foo {
    double value;
    double GetValue() const { return value; };
    void SetValue(double NewValue) const { value = NewValue; };

My exported DLL functions could look like this:

typedef Foo* FOO_HDL;

extern "C" { 

__declspec(dllexport) FOO_HDL __stdcall FooCreate() {
  return new Foo();

__declspec(dllexport) void __stdcall FooDestroy(FOO_HDL obj) {
  delete obj;

__declspec(dllexport) double __stdcall FooGetValue(FOO_HDL obj) {
  return obj->GetValue();

__declspec(dllexport) void __stdcall FooSetValue(FOO_HDL obj, double NewValue) {


But, to be really safe, you also need to make sure that no exceptions leave the DLL boundary. So, in theory, you would need to wrap all the bodies of all the exported functions with a catch-all clause, as such, for example:

void __stdcall FooSetValue(FOO_HDL obj, double NewValue) {
  try {
    obj->SetValue(NewValue); //if this operation throws an exception, it must not propagate further.
  } catch(...) {             //so, catch all exceptions.
    //do something.. or not.

But, the above is a bit tedious and few people do it. If an exception occurs and you don't catch it before the boundary of the DLL is traversed back during stack unwinding, you will get a crash (in some case that's acceptable, in others, it is not).

Edited by mike_2000_17: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.