您的位置:首页 > 编程语言 > C语言/C++

C++ 调用c#DLL函数

2012-08-07 16:51 351 查看
自己实践了一下,其实不是很难,怕自己忘记掉,再加上有几个需要注意的问题,这里记录下来。

1. c# 创建dll library

using System;
using System.Collections.Generic;
using System.Text;

namespace AddDll
{
public class Add
{
public int iadd(int a, int b)
{
int c = a + b;
return c;
}
}
}


2. c++实现调用程序

这里创建一个Win32的控制台应用程序

Configure:右键点击解决方案资源管理器中的UseDll,选择“属性”,将公共语言运行库支持设置为“公共语言运行库支持(/clr)”
即Common Language Runtime Support (/clr)

PS:如果你是建立一个MFC程序的话,必须把Use of MFC设置成:Use MFC in a Shared DLL 共享dll,不然会引起冲突

(error D8016: '/clr' and '/MTd' command-line options are incompatible 错误)

#include "stdio.h"

#using "..\debug\AddDll.dll"
using namespace AddDll;

int main(){
int result;
Add ^add = gcnew Add();   //生成托管类型
//gcnew creates an instance of a managed type (reference or value type) on the garbage //collected heap. The result of the evaluation of a gcnew expression is a handle (^) to //the type being created.        result = add->iadd(10,90);
printf("%d",result);
scanf("%s");
return 0;
}


Attention:

1. 使用#using引用dll,而不是#inculde。

2. 别忘了using namespace CSLib

3. 使用C++/clr语法,采用正确的访问托管对象,即:使用帽子‘^’,而不是星星‘*’。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: