c# - VS2010中的Marshal结构体指针

标签 c# visual-studio-2010 pinvoke marshalling

我必须从我的 C# 程序中调用 C++ DLL。 我正在尝试使用 PInvoke 来完成此操作 - 在 VS2005\2008 中一切正常,但在迁移到 VS 2010 后,出现此异常:

PInvokeStackImbalance was detected Message: A call to PInvoke function 'sampleFunc' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

这是原始的 C++ 原型(prototype):

typedef struct {
    unsigned short field1;
    unsigned short field2;
} sInfo;

_declspec(dllexport) int sampleFunc(sInfo *info, char *txt);

这是 C# 代码:

[StructLayout(LayoutKind.Sequential)]
    struct SInfo
    {
        //[MarshalAs(UnmanagedType.U1)] //also tried with the MarshalAs attr. Didn't help.
        public ushort field1;
        //[MarshalAs(UnmanagedType.U1)]
        public ushort field2;
    };
[DllImport("sampleModule.dll", CharSet=CharSet.Ansi)]
        public static extern int sampleFunc(ref SInfo info, [MarshalAs(UnmanagedType.LPStr)] string txt);

我也尝试过使用 IntPtr 而不是 ref SInfo,但得到了相同的结果......

任何帮助将不胜感激,

谢谢大家!

最佳答案

很难看出这在以前是如何运作的。 C++ 声明不声明调用约定,默认值为 __cdecl,除非在 C++ 项目中使用/Gz 编译选项覆盖。您必须告诉 P/Invoke 编码器:

    [DllImport("sampleModule.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    public static extern int sampleFunc(ref SInfo info, string txt);

关于c# - VS2010中的Marshal结构体指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2999338/

相关文章:

.net - .NET PInvoke 能否从用户指定的目录动态加载 native dll?

c# - c#写mysql建表查询的方法

c# - 注释会减慢编译语言的速度吗?

visual-studio - 防止 Visual Studio 尝试在 PDF 文件中作为二进制数据进行搜索

c# - 如何获得打开网页的按钮?

c# - 对 PInvoke 函数 'Test!DllCall::initDll' 的调用使堆栈失衡

c# - 如何在插入语句中使用子查询

c# - 服务中的定时器

c++ - 如何为当前打开的窗口模拟鼠标滚动?

c# - P/Invoke 返回 void*