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

这篇文章没有什么新意,在2004年的时候就有人写过那时候VS还只是2003版,而且网络上也有很多转来转去的文章,其实一共那么两三篇。其实我也是从那里学来的,只不过中间经历的一些郁闷,因为那些文章没有提到一些注意的事项确是很烦人。
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(
23ref c));
            Console.Read();
        }

    }

}
最后你会看到运行结果:5。
请注意绿色字体内容,祝你好运。
posted @ 2008-02-29 23:50  moonz-wu  阅读(2494)  评论(3编辑  收藏  举报