C#调用C++动态库2-C# exe调用C++dll

1、创建一个新的项目
在这里插入图片描述
2、

问题描述:

   在使用托管代码调用非托管代码时,发生“对 PInvoke 函数“UseTwiHikVisionDllTest!UseTwiHikVisionDllTest.TwiHikVision::GetFirstPic”的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标签名是否匹配。”

解决方法:

 添加属性: CallingConvention=CallingConvention.Cdecl

如:
[DllImport(“TwiHikVision.dll”, EntryPoint=“GetFirstPic”, CallingConvention=CallingConvention.Cdecl)]
public static extern string GetFirstPic(string videoFileName, string exportFilePath);

3、"Interface.dll"是C++生成的DLL,复制到C#工程bin中
"GetStringReturn1"为C++中函数的名称
“ public static extern System.IntPtr GetStringReturn1();”
在C#中函数和方法的声明
4、int可以直接用
cha*和string 需要转换
//字符串转换成IntPtr 指针
IntPtr valPtr = Marshal.StringToHGlobalAnsi(“this is beautiful day”);
IntPtr work = fnSampleDLL(valPtr);
//指针转换成字符串
string work1 = Marshal.PtrToStringAnsi(work);

5、实列代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
public class DLL
{
[DllImport(“Interface.dll”, EntryPoint = “GetStringReturn1”)]
public static extern System.IntPtr GetStringReturn1();

[DllImport("Interface.dll", EntryPoint = "Sub",CallingConvention=CallingConvention.Cdecl)]
public static extern int Sub(int x, int y);//与dll中一致
//public extern static string GetStringReturn1();//与dll中一致 

}

namespace Interface2
{
class Program
{
static void Main(string[] args)
{
//字符串传递
IntPtr work = DLL.GetStringReturn1();
//指针转换成字符串
string work1 = Marshal.PtrToStringAnsi(work);
Console.WriteLine(work1);
//整型的传递
int ret = DLL.Sub(4, 3);
Console.WriteLine(ret);
Console.ReadKey();
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

和光同尘 、Y_____

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值