c# 与 c++ 交互

一个net项目可能用到多种语言。今天无聊就看了下c++与c#的交互。写了个小的demo。


 

用vs2010 新建一个空的解决方案。右击解决方案添加 ,在visual c++下选择win32项目。名字为csharpCallCPlusPlusDll。下一步,选择DLL。确定。

然后在头文件新建一个csharpCallCPlusPlusDll.h文件。

#ifndef BonkerDLL
#define BonkerDLL extern "C" _declspec(dllexport)
#endif

BonkerDLL int Sum(int sum1,int sum2);

  

此代码的意思是给外部调用的c#程序提供接口。


然后在csharpCallCPlusPlusDll.cpp文件里面添加代码

#include "stdafx.h"
#include "MathHelp.h"

int Sum(int arg1,int arg2)
{
	return arg1+arg2;
}

  生成就ok了。


在解决方案下添加win32的c#项目,名字为ConsoleApplication1。代码如下


 class Program
    {
        [DllImport("csharpCallCPlusPlusDll.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int Sum(int num1, int num2);

        static void Main(string[] args)
        {
            Console.WriteLine(Sum(3,58));
            Console.ReadKey();
        }
    }

  此时要更改c++类库的生成路径,右键属性-》配置属性-》常规 -》输出目录  改成..\ConsoleApplication1\bin\Debug\


最后设置c#项目为启动项目。运行下就ok了。

 

详细见http://www.soaspx.com/dotnet/csharp/csharp_20110406_7469.html

 

 

posted @ 2013-06-26 16:51  Bonker  阅读(1514)  评论(0编辑  收藏  举报