C + + and C # mixed generation. NET Program

Source: Internet
Author: User
c++| program

This article provides a way to get C + + source and C # code together to compile the link into a single assembly.
Because C + + provides a IJW method that allows the old C + + code to be compiled into managed code, this text can be used to completely resolve all C + + legacy code porting to. NET's problem.
This method, plus the previous text, "Do you also use managed C + +?" , you can migrate the C + + legacy code to. NET all the methods are catch.

Okay, here we are.
Suppose a very simple C + + program, which has only one function:

C.h
#pragma once
int sqr (int n);

C.cpp
#include "c.h"
int sqr (int n)
{
return n*n;
}
In order for it to work with C #, it must be added to it. NET's packaging:

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 invoke it:

Cs.cs
Using System;
Namespace test
{
public class Program
{
public static void Main ()
{
Console.WriteLine (WRAPPER.CALC.SQR (11));
}
}
}

Now, how to compile these source code into an EXE file?
The integration environment is difficult, most convenient, or to create a makefile to complete.
Because 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
Generate Cs.netmodule

Link C.obj wrapper.obj cs.netmodule/ltcg/subsystem:console/entry:test. Program.main/out:o.exe
Generate O.exe

Run O.exe Display results: 121

------
Mu Maple Small build C + + and C # hybrid generation. NET Program

Resources:
1. netmodule Files as Linker Input http://msdn2.microsoft.com/en-us/library/k669k83h (vs.80). aspx
2. Select the format of the. netmodule input file http://msdn2.microsoft.com/zh-CN/library/0zyh2sf2 (vs.80). aspx







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.