Question

I have a C++ native dll where a structure is defined as follows:

typedef struct
{
int x;
int y;
unsigned short* orange;
}SET_PROFILE;

And a function in the C++ dll as:

extern "C" _declspec(dllexport) void modifyClass(SET_PROFILE** input)
{
    *input = &globPro;  
}

where globPro is a global object of type SET_PROFILE and its member orange is "ABC".

I have redefined this structure on the C# side as a class:

[StructLayout(LayoutKind.Sequential)]
public class SET_PROFILE
{
    public int x;
    public int y;
    public String orange;
}

and pinvoking the function:

[DllImport("Project2.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void modifyClass(out IntPtr input);

When I call this function and then marhal it back to the structure:

IntPtr classPtr = IntPtr.Zero;
classPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SET_PROFILE)));
modifyClass(out classPtr);
profile1 = (SET_PROFILE)Marshal.PtrToStructure(classPtr, typeof(SET_PROFILE));

Now, profile1's orange meber just has "A" instead of "ABC". It has something to do with how it's copied using pointers. I can't modify the C++ function however. Is it because I used a string as the member of the C# class instead of unsigned short[]. I tried that too but failed.

Was it helpful?

Solution

Try using the following:

[StructLayout(LayoutKind.Sequential)]
public class SET_PROFILE
{
    public int x;
    public int y;

    public System.IntPtr orange;    
    public string OrangeString { get { return Marshal.PtrToStringAnsi(orange); } }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top