Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# P/Invoke调用失败_C#_C++_Struct_Pinvoke - Fatal编程技术网

C# P/Invoke调用失败

C# P/Invoke调用失败,c#,c++,struct,pinvoke,C#,C++,Struct,Pinvoke,我在C++中定义了以下结构: struct GraphicsAdapterDesc { // ... Just some constructors / operators / destructor here DEFINE_DEFAULT_CONSTRUCTOR(GraphicsAdapterDesc); DEFINE_DEFAULT_DESTRUCTOR(GraphicsAdapterDesc); ALLOW_COPY_ASSIGN_MOVE(GraphicsAd

我在C++中定义了以下结构:

struct GraphicsAdapterDesc {
    // ... Just some constructors / operators / destructor here
    DEFINE_DEFAULT_CONSTRUCTOR(GraphicsAdapterDesc);
    DEFINE_DEFAULT_DESTRUCTOR(GraphicsAdapterDesc);
    ALLOW_COPY_ASSIGN_MOVE(GraphicsAdapterDesc);

    std::wstring AdapterName;
    int32_t AdapterNum;
    std::wstring HardwareHash;

    int64_t DedicatedVMEM;
    int64_t DedicatedSMEM;
    int64_t SharedSMEM;

    int32_t NumOutputs;
};
在C#中,我声明了一个“镜像”结构:

[StructLayout(LayoutKind.Sequential)]
public struct GraphicsAdapterDesc {
    string AdapterName;
    int AdapterNum;
    string HardwareHash;

    long DedicatedVMEM;
    long DedicatedSMEM;
    long SharedSMEM;

    int NumOutputs;
};
在匹配变量的宽度时,我一直非常小心(尽管我有点不确定如何准确地处理字符串)

无论如何,我有以下导出的C方法:

extern "C" __declspec(dllexport) bool GetGraphicsAdapter(int32_t adapterIndex, GraphicsAdapterDesc& outAdapterDesc) {
    outAdapterDesc = RENDER_COMPONENT.GetGraphicsAdapter(adapterIndex);
    return true;
}
下面是我的C#app中的
extern
方法:


然而,当我调用它时,这并不正确。根据X64或x86模式编译(C++ + DLL和C语言应用程序都编译为x86或x64),得到不同的结果:

  • 在x86模式下,调用返回,但结构中有“无意义”值,且字符串均为null
  • 在x64模式下,调用抛出NullPointerException
我的期望是,我在编组字符串时出错,需要为字符指定“宽模式”,但我不知道如何(或者这是否是正确的选项)


先谢谢你> P> C++类型与C语言不兼容,除非它们被包在托管C++中。您使用的是无法封送到.NET中的
std::wstring

要成功地进行互操作,您需要使用
wchar\u t[]
whar\u t*
并告诉C立即封送它

[DllImport(InteropUtils.RUNTIME_DLL, EntryPoint = "GetGraphicsAdapter", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool _GetGraphicsAdapter(int adapterIndex, out GraphicsAdapterDesc adapterDesc);