I'm trying to use P/Invoke to populate a POD struct. The POD struct in C++ looks like this:
struct GraphicsAdapterDesc {
const wchar_t* AdapterName;
int32_t AdapterIndex;
const wchar_t* HardwareHash;
int64_t DedicatedVMEM;
int64_t DedicatedSMEM;
int64_t SharedSMEM;
int32_t NumOutputs;
};
I've tried to be careful with explicitly specifying the widths of all my fields. The 'mirror' struct, in C#, is defined as follows:
[StructLayout(LayoutKind.Sequential)]
public struct GraphicsAdapterDesc {
public WCharStringPtr AdapterName;
public int AdapterIndex;
public WCharStringPtr HardwareHash;
public long DedicatedVMEM;
public long DedicatedSMEM;
public long SharedSMEM;
public int NumOutputs;
};
Where WCharStringPtr looks like this:
public struct WCharStringPtr {
internal IntPtr charArrayPtr;
private string asString;
public string AsString {
get {
return asString ?? (asString = Marshal.PtrToStringUni(charArrayPtr));
}
}
public static implicit operator string(WCharStringPtr operand) {
return operand.AsString;
}
public override string ToString() {
return AsString;
}
}
I have a method defined as such in C++:
extern "C" __declspec(dllexport) bool GetGraphicsAdapter(int32_t adapterIndex, GraphicsAdapterDesc& outAdapterDesc) {
outAdapterDesc = RENDER_COMPONENT.GetGraphicsAdapter(adapterIndex);
return true;
}
And the P/Invoke extern method declaration is as follows:
[DllImport(InteropUtils.RUNTIME_DLL, EntryPoint = "GetGraphicsAdapter", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool _GetGraphicsAdapter(int adapterIndex, out GraphicsAdapterDesc adapterDesc);
Whenever I call _GetGraphicsAdapter, I get an access violation error (not an AccessViolationException). When I break the program from within the extern C++ method, everything appears to be well-formed; but as soon as I return from that method, the access violation occurs. So, I'm guessing that there's some memory being cleaned up as soon as the method exists, but I can't see what, or why.
Then again, I'm new to P/Invoke, and maybe it's something to do with my handling of strings; I'm not exactly sure if what I'm doing is correct.
Thank you in advance.