c#调用c++库,接口包含结构体指针类型的形参处理方式

6 篇文章 0 订阅
6 篇文章 0 订阅

c++ 类型是非拖管的,需要做封送处理,才可以在c#中使用

详细介绍见:https://blog.csdn.net/sgzwiz/article/details/40980771

举个例子,

在c++库中定义一个结构体,一个接口函数bool Func(MyStruct* temp),并将其导出,导出方式见博文https://mp.csdn.net/console/editor/html/105665917

struct MyStruct
{
	int* _pBuff;
	int num;
};
bool Func(MyStruct* temp)
{
	temp->_pBuff = 0;
	temp->num = 10;
}

在C# 中定义如下

开辟的字节大小根据类型定义的不同而不同,注意需要选择正确的字节大小。

    [Serializable]
    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    public struct MyStruct
    {
        [MarshalAs(UnmanagedType.SysInt)]
        public IntPtr _pBuff;
        [MarshalAs(UnmanagedType.I4)]
        int num;
    };
public class Base
    {
        [DllImport(@"***.dll", EntryPoint = "Func", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        public static extern unsafe bool Func(out IntPtr temp);
        public static bool Func(ref MyStruct temp)
        {
            int size = Marshal.SizeOf(typeof(MyStruct));
            IntPtr pBuff = Marshal.AllocHGlobal(size);
            IntPtr p = new IntPtr(pBuff.ToInt64() + size);
            Marshal.StructureToPtr(temp, p, false);
            bool code = Base.Func(out pBuff);
            Marshal.FreeHGlobal(pBuff);
            return code;
        }
    }

 

MyStruct temp = new MyStruct();
bool rel = Base.Func(ref temp);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值