C# P/Invoke调用失败
我在C++中定义了以下结构: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
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
先谢谢你我不知道你的宏在做什么,但是如果你的C++是这样的话,这只会起作用。c++11具有扩展的POD概念,但我认为您无论如何都不符合扩展的标准。否则,您无法保证布局。如果你想把C++类导出到C语言,我建议你使用C++ +CLI。此外,您的语句中定义了wstring,这绝对不是POD。当您使用DLLImport时,请只考虑C构造,否则您将度过一段不愉快的时光> 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);