我在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;
}下面是我的extern应用程序中的C#方法:
[DllImport(InteropUtils.RUNTIME_DLL, EntryPoint = "GetGraphicsAdapter", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool _GetGraphicsAdapter(int adapterIndex, out GraphicsAdapterDesc adapterDesc);然而,当我称之为它的时候,这是不正确的。根据是否以x64或x86模式编译( C++ DLL和C#应用程序都编译为x86或x64),我得到了不同的结果:
我的期望是,我做错了字符串编组,我需要为字符指定“宽模式”,但我不知道如何(或者这是否是正确的选项)。
提前谢谢你。
发布于 2014-01-31 17:57:57
C++类型与C#不兼容,除非它们被包装在托管C++中。您使用的是std::wstring,它不能封送到.NET中。
要成功地互操作,您要么需要使用wchar_t[]或whar_t*,然后告诉C#立即对其进行封送。
发布于 2014-01-31 17:56:08
我不知道您的宏在做什么,但是只有当您的c++类型是吊舱时,这才能起作用。c++11有一个扩展的意义,但我认为你不符合扩展的标准无论如何。否则你不能保证布局。如果您想将c++类导出到C#,我建议您使用c++\cli。此外,您在结构中定义了wstring,这肯定不是POD。当您使用DLLImport时,只考虑C结构,否则就会遇到麻烦。
https://stackoverflow.com/questions/21486743
复制相似问题