Translating a C++ header for a DLL into C#

I have to following C++ header that corresponds to a DLL that I'm trying to use in C#.

class __declspec(dllimport) Value {
std::string bytes;
public:
Value();
void setValue(BYTE* val, int length);
int size();
BYTE* getBytes();
};

How do I import that class into C# In particular, I'm having trouble figuring out the constructor. The compiler says that I can only use DllImport with static methods...

Also, how do I translate the Byte pointers into C#

So far, I've gotten:

public class Value {

string bytes;

[DllImport("PCMPlusAPI.dll", EntryPoint = " 0Value@@QAE@XZ")]

static extern IntPtr Value_Constructor();

[DllImport("PCMPlusAPI.dll", EntryPoint = " setValue@Value@@QAEXPAEH@Z")]

extern void setValue (Byte* val, int length);

[DllImport("PCMPlusAPI.dll", EntryPoint = " size@Value@@QAEHXZ")]

extern int size();

[DllImport("PCMPlusAPI.dll", EntryPoint = " getBytes@Value@@QAEPAEXZ")]

extern char* getBytes();

}

But that doesn't work both because of the non-static methods, and the Byte pointers.

Help is much appreciated. =)



Answer this question

Translating a C++ header for a DLL into C#

  • Rajesh Prabhu. R

    Hi!

    You can't use P/Invoke to call C++ classes directly. C++ class is basically different than C# (.NET) class - in .NET there is automatic memory cleanup and other features, which completely change basement. C++ DLL will contain prepared machine codes, while .NET assembly contains IL code, that translated to machine code later during execution.

    I think best way is to port C++ source to C# (if possible) or write C++ DLL that use Pascal (WinAPI) calling style (and no classes) and then use P/Invoke.


  • Translating a C++ header for a DLL into C#