本文提供了一個方法,讓c++源碼和c#源碼一起編譯鏈接成一個單一的assembly。
由于c++提供了ijw方法,允許將舊有c++代碼也編譯成托管代碼,因此這篇小文可以用極小的工作量來徹底解決所有c++遺留代碼移植到.net的問題。
這個方法,再加上前次的小文《您也使用托管c++嗎?》,就可以把c++遺留代碼移植到.net的所有方法一網(wǎng)打盡了。
好了,言歸正傳。
假設(shè)一個很簡單的c++程序,它只有一個函數(shù):
//c.h
#pragma once
int sqr(int n);
//c.cpp
#include "c.h"
int sqr(int n)
{
return n*n;
}
為了能讓它與c#共同工作,必須為它加個.net的包裝:
//wrapper.cpp
#include "c.h"
namespace wrapper
{
public ref class calc
{
public:
static int sqr(int n)
{
return ::sqr(n);
}
};
}
現(xiàn)在可以用c#去調(diào)用它了:
//cs.cs
using system;
namespace test
{
public class program
{
public static void main()
{
console.writeline(wrapper.calc.sqr(11));
}
}
}
現(xiàn)在,如何將這些源碼編譯成一個exe文件呢?
用集成環(huán)境是很難的,最方便的,還是創(chuàng)建一個makefile來完成。
由于這個例子很簡單,我用命令行來創(chuàng)建這個exe文件:
cl c.cpp wrapper.cpp /c /clr
生成 c.obj 和 wrapper.obj
csc /addmodule:wrapper.obj /target:module /out:cs.netmodule cs.cs
生成 cs.netmodule
link c.obj wrapper.obj cs.netmodule /ltcg /subsystem:console /entry:test.program.main /out:o.exe
生成 o.exe
運(yùn)行 o.exe 顯示結(jié)果:121
------
沐楓小筑 c++與c#混合生成.net程序
參考資料:
1. .netmodule files as linker input http://msdn2.microsoft.com/en-us/library/k669k83h(vs.80).aspx
2. 選擇 .netmodule 輸入文件的格式 http://msdn2.microsoft.com/zh-cn/library/0zyh2sf2(vs.80).aspx
新聞熱點(diǎn)
疑難解答
圖片精選