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

在VS2008中编译纯c/c++程序并由c#调用过程

2010-07-10 10:49 501 查看
1. 建立一个C#控制台工程,主要用于调试。

2. 在解决方案中添加一个新的空工程(VC++的)。

3. 添加一个源文件到Source Files文件夹(xxx.c or xxx.cpp)。

4. 加入这行代码

#include <string.h>

extern "C" __declspec(dllexport) int mySum(int a,int b,int *c)
{
*c=a+b;
return *c;
}


由于原来的文章没有提,导致我缺了#include <string.h>而编译出错,花了点时间修正这问题。

5. 右键点击C++工程,在属性中的General->Configuration Type 选择 Dynamic Library (.dll)。这里还要注意的是为了编译生成的dll文件能被c# 工程导入你需要Common Language Runtime support 选择Common Language Runtime Support (/clr)这项,否则编译的dll不能用到c#工程当中。

6. build C++工程(你也可以用命令行CL.exe来编译文件)。之后,有很多人就直接向当然的跑到c++工程下面的Debug文件夹里去找xxx.dll文件,结果只看到xxx.dll.intermediate.manifest这样的文件失望而归。其实编译后真正的dll文件是在解决方案的Debug文件夹下面。

7. 在c#工程的引用中导入xxx.dll。在c#主文件中键入如下代码:我这里的xxx = CCodeDll

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

namespace TestEmbedCCalling
{
class Program
{
[DllImport("CCodeDll.dll", EntryPoint = "mySum", CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.StdCall)]
public static extern int mySum(int a, int b, ref int c);

static void Main(string[] args)
{
int c = 0;
Console.WriteLine(mySum(2, 3, ref c));
Console.Read();
}
}
}


最后你会看到运行结果:5。

请注意绿色字体内容,祝你好运。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: