VS2010C#调用C++ dll关于.Net版本问题

本文介绍如何解决C++ DLL在C#中调用时出现的问题,包括.NET版本选择、调用约定设置等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在利用C++创建一个dll项目后编译生成dll后,拷贝到已建好的C#程序中准备调用时,会出现这样那样的问题。由于我是刚上手不太了解,第一次用时,按照网上的一些方法写了一个测试代码,C++的代码如下

MyDLL.cpp

#include "stdafx.h"
extern "C" __declspec(dllexport) int ADD(int a, int b)
{
	return a + b;
}

编译生成相应的DLL

在C#中进行调用,代码如下

CPPDll类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace DllTest
{
    class CPPDll
    {

        [DllImport("MyDll.dll"]
        public static extern int ADD(int x, int y);
    }
}
        private void button2_Click(object sender, EventArgs e)
        {
            int result = CPPDll.ADD(10, 20);
            MessageBox.Show(Convert.ToString(result));
        }

然后开始运行,此时C#默认的.Net为4.0 Client Profile ,运行过程中出现如下错误

然后将C#的.Net修改为3.5在运行则顺利成功

然后我就到网上查了一下为什么会出现这种问题,后来参考http://blog.sina.com.cn/s/blog_48cc2a81010167pm.html这篇文章里的一些方法将CPPDll中的代码修改为

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace DllTest
{
    class CPPDll
    {

        [DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int ADD(int x, int y);
    }
}

即在 DllImport加了参数 CallingConvention = CallingConvention.Cdecl然后再运行就可以了。但是其中具体什么原因就不是很清楚了,希望有高手给解释一下其中的缘由啊!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值