Lopper
Lopper

Reputation: 3537

How to call native VC++6 library (with std::string as parameters) from C#

I have a native dynamic link library written in VC++6 and I do not have access to the source code. I would like to convert it to managed code so that C# can call this library. The problem is that the VC6 library heavily makes use of std::vector and std::string as function parameters and there is no way of marshaling these types into C# directly.

So what I need is a bridge between VC6 and C# and I implemented a VC++2005 wrapper for VC++6.

However, I realized from the reply (by jalf) to the following thread that "VC++6 and VC++2005 have different definitions of std::string (and the compilers may also insert different padding and other changes), and the result is garbage, and/or unpredictable behavior and crashes".

Passing std::string from VC++2005 to VC++6 DLL results in garbage

So now, the big question is, how can I call the VC++6 native library from C#?

I am at a loss and any help is greatly appreciated.

Upvotes: 2

Views: 309

Answers (1)

dtroy
dtroy

Reputation: 1227

If you've got access to VC++6, compile the "bridging/wrapper" dll with that. Then, expose functions with types you can P/Invoke from C# such as Char* etc..

BTW, You can probably get a "used" license on eBay or something for cheap.

EDIT:
Here's a sample code for what you've asked (I think...):

[System.Runtime.InteropServices.DllImport("somedll.dll")]
public static extern int Fun1(int n, IntPtr[] lpNames);


//////////////////////////////////////////////////////////////////////////
List<string> strList = new List<string>();

IntPtr[] strPointerArr = new IntPtr[strList.Count];
for(int i=0; i<strList.Count; ++i){
    strPointerArr[i] = System.Runtime.InteropServices.Marshal.StringToHGlobalUni(strList[i]);
}
Fun1(strList.Count, strPointerArr);

//////////////////////////////////////////////////////////////////////////

Upvotes: 2

Related Questions