This article provides a method for linking C ++ source code with C # source code to a single assembly.
Because the C ++/CLI of M $ provides the ijw methodCodeAlso compiled into managed code, so this article can use a very small amount of work to completely solve the problem of porting all c ++ legacy code to. net.
This method, coupled with the previous article 《Do you also use hosting C ++?, You can port all the methods of C ++ to. net.
Now, let's get down to the truth.
Suppose a very simple C ++ProgramIt has only one function:
// C. h
# Pragma once
Int Sqr ( Int N );
// C. cpp
# Include " C. h "
Int Sqr ( Int N)
{
ReturnN*N;
}
To make it work with C #, you must add a. Net Package for it:
// Wrapper . Cpp
# Include " C. h "
Namespace Wrapper
{
Public Ref Class Calc
{
Public :
Static Int Sqr ( Int N)
{
Return: Sqr (N );
}
} ;
}
Now you can use C # To call it:
// CS. CS
Using System;
Namespace Test
{
Public Class Program
{
Public Static Void Main ()
{
Console. writeline (wrapper. Calc. sqr (11));
}
}
}
How do I compile these source codes into an EXE file?
it is very difficult to use an integrated environment. It is most convenient to create a makefile or msbuild.
as this example is very simple, I use the command line to create this EXE file:
Cl C. CPP wrapper. CPP/C/CLR
Generate C. OBJ and wrapper. OBJ
CSC/addmodule: wrapper. OBJ/Target: module/out: CS. netmodule CS. CS
generates CS. netmodule
link C. OBJ wrapper. obj cs. netmodule/ltcg/subsystem: console/entry: test. program. main/out: o.exe
generates o.exe
RUN o.exe to display the result:
121
------
C ++ and C # generate a. Net Program
References:
1. netmodule files as linker input http://msdn2.microsoft.com/en-us/library/k669k83h (vs.80). aspx
2. Select format http://msdn2.microsoft.com/zh-CN/library/0zyh2sf2 (vs.80). aspx for the. netmodule input file
Postscript: (2006-04-19)
I checked it on the Internet and found this introduction. For more information, see.
Original address: http://blog.joycode.com/junfeng/archive/2005/05/25/51838.aspx? Pending = true