Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

wrapper for c++ to c#

Status
Not open for further replies.

diembi

Programmer
Sep 22, 2001
238
ES
Hello,

I'm new in c#-c++ marshaling and wrappers. I need to use a c++ dll where there are the next header and struct:

extern "C" __declspec(dllexport) int GiveMeData(LPCTSTR sID, CustomerData* pData)


typedef struct CustomerData
{
LPTSTR customerName
LONG customerItems;
}


In C#, is correct the next wrapper?


[DllImport("Customers.dll")]
public static extern int GiveMeData(string sID, ref CustomerData pData);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CustomerData
{
public string customerName;
public int customerItems;
}


If isn't correct, how is the best way for do it avoiding possibles heap corruptions, etc?

Thank you!!!!
 
You might have a problem with customerName, because of .NET string's immutable nature. It would seem that the native DLL will be setting the value of customerName. You can try substituting that with StringBuilder.
 
You probably need to marshal the strings. I've never used C pointers: only fixed sized arrays. Possibly something like
Code:
[DllImport("Customers.dll")]
public static extern int GiveMeData(
   //                                 ,--  Depending on whether you are
   //                                 |    using unicode.  If not use byte
   [MarshalAs(UnmanagedType.LPArray)] char[] sID, 
   ref CustomerData pData);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CustomerData
{
   // If array of known size, say 16 then add something like
   // [MarshalAs(UnmanagedType.ByValTStr, SizeConst=16)]
   public string customerName; 
   public int customerItems;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top