views:

184

answers:

1

This is my c++ struct (Use Multi-Byte Character Set)

typedef struct hookCONFIG {
    int threadId;
    HWND destination;

    const char** gameApps;
    const char** profilePaths;
} HOOKCONFIG;

And .Net struct

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct HOOKCONFIG {
    public int threadId;
    public IntPtr destination;

    // MarshalAs?
    public string[] gameApps;

    // MarshalAs?
    public string[] profilePaths;
}

I got some problem that how do I marshal the string array? When I access the struct variable "profilePaths" in C++ I got an error like this:

An unhandled exception of type 'System.AccessViolationException' occurred in App.exe

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

MessageBox(0, cfg.profilePaths[0], "Title", MB_OK); // error ... Orz
A: 

Easy way: Change prototype to IntPtr[]:

public IntPtr[] gameApps;
public IntPtr[] profilePaths;

Now when you call you need to roughly the following psudo-code:

GCHandle handle = GCHandle.Alloc(string);
gameApps = new IntPtr[] { GCHandle.ToIntPtr(handle) };

// Unmanaged call

handle.Free();
csharptest.net