How to use C ++ classes (unmanaged) and c Functions in C #

Source: Internet
Author: User
Tags hosting

Since C # is writing managed code, it is compiled to generate a Microsoft intermediate language, c ++ code is compiled to generate local machine code (such C ++ is also called local C ++ or unmanaged C ++, vc6.0 is a platform for developing unmanaged C ++ Code). It is difficult to perform mixed programming in these two languages. The most common method is to use the dllimport method, which is described on the Internet. However, anyone who has used this method knows that this method can export functions, but cannot export unmanaged C ++ classes! Very terrible.

Recently, when I was working on a project, I encountered the need to use an unmanaged C ++ class in the C # code. Most of the collected information (from csdn) I found a way to export the class of the unmanaged C ++ code to C. Now, we can simply make a learning summary to provide a reference for colleagues who encounter similar problems.

The above has already said why it is difficult for C # To directly call an unmanaged C ++ class. However, in addition to C # and unmanaged C ++, there is also a language (personal opinion) in the C series called hosting C ++, the syntax of this language is almost the same as that of unmanaged C ++, but it is compiled into a Microsoft intermediate language like C #, so that C ++ can communicate well with C, you can use the hosted C ++ class in C. In addition, hosting C ++ has two important features: Calling classes and functions of unmanaged C ++! The C ++-hosted assembly can nest the machine code compiled by the unmanaged C ++! A powerful mix. Therefore, our technical path is clear: C # uses hosted C ++ as an intermediary to call classes and functions of unmanaged C ++. In other words, the hosted C ++ is used to make a shell package for the unmanaged C ++ code for the C # Call.

 

In our example, a function is signed as a C function of int add (int A, int B) and an unmanaged C ++ class.
Cclassnative is exported and used in C.

To achieve this goal, we will build a project for demonstration.

1. Prepare the classes and functions for export.

First, create a Win32 C ++ project, the project is "win32application (C, C ++)", the solution is "C, C ++, CSHARP mixed programming demonstration ".

1) AddFunctions. hFile andFunctions. cppFile, inFunctions. hIntadd (int
A, int B); InFunctions. cppWrite and implement add (int A, int B). Code:

Functions. hFile:

// The C function int add (int A, int B) used for export is defined here );

Functions. hFile:

# Include "stdafx. H" # include "functions. H" // here the C function (arithmetic addition) int add (int A, int B) {return a + B ;}

2) create a C ++ unmanaged class, cclassnative

InClassnative. hClass:

# Pragma onceclass cclassnative {public: cclassnative (void );~ Cclassnative (void); int menber; // The Int menderfuncsub (int A, int B) member for export; // The member function for export to implement arithmetic subtraction };

InClassnative. cppWrite code in:

# Include "stdafx. H" # include "classnative. H" cclassnative: cclassnative (void) {// construct menber = 1;} cclassnative ::~ Cclassnative (void) {}// this is an arithmetic subtraction of the non-hosted C ++ class implementation int cclassnative: menderfuncsub (int A, int B) {return a-B ;}

In this way, very simple unmanaged C ++ classes and functions are ready. Now we need to wrap these classes and functions using managed C ++.

2. Use hosted C ++ to package unmanaged C ++ classes and C functions.

To use managed C ++, You need to edit the translation option: click the "win32application (C, C ++)" project and select "attribute" in the shortcut ", select "configuration properties"> "general"> "common language runtime support" as "common language runtime support (/CLR )".

3) create a class hosting class clrclass

InClrclass. hFile definition:

# Pragma once # include "classnative. H "// This Is A hosted C ++ class used to encapsulate C ++ local code classes and functions to use public ref class clrclass in C # // It must be declared as public, otherwise, the class is invisible in the Assembly. The keyword ref indicates that the class is a Managed class and will be compiled into an intermediate language {public: clrclass (void); int menber; // This member accesses the public members of the unmanaged class cclassnative (in fact, only public members and public member functions need to be packaged. Private packaging is meaningless and cannot be packaged) int menderfuncsub (int, int B); // This member function is used to wrap the public member function int menberfuncadd (int A, int B) of the unmanaged class cclassnative )); // This member function is used to wrap the C function int add (int A, int B) Private: cclassnative * classnative; // create an unmanaged class instance (instantiated in the constructor, it can be understood as "Inheriting" the public members and methods of cclassnative in clrclass )};

InClrclass. cppWrite in the file:

# Include "stdafx. H "# include" clrclass. H "# include" functions. H "clrclass: clrclass (void) {classnative = new cclassnative (); // You must create an object here! Menber = classnative-> menber; // here is a simple example. It is best to use the attribute method to read and write members of the cclassnative class. Similar to C #, it hosts attribute functions in C ++, please check the usage} // call the unmanaged class cclassnative subtraction function to implement the arithmetic subtraction int clrclass: menderfuncsub (int A, int B) {return classnative-> menderfuncsub (, b);} // implement arithmetic addition by calling the C function int clrclass: menberfuncadd (int A, int B) {return add (a, B );}

In this way, the clrclass implements the managed packaging for the cclassnative class and the C function int add (INTA, int B. The generated "win32application (C, C ++). dll" can be used directly in C.

3. Locally packaged C ++ classes and C functions in C.

To test the effect, we have created a C # project "windowsformsapplication (CSHARP)" in this solution to see the effect. This project is a "Windows Forms Application". It aims to call the int add (INTA, int B) function of C for addition. The Int menderfuncsub (int A, int B) of cclassnative) the member function is used for subtraction. The interface design is as follows.

Add a reference to "win32application (C, C ++). dll" in "Reference" of "windowsformsapplication (CSHARP.

Since C # Is probably familiar to everyone, other steps are omitted. Only the event handler functions for creating clrclass objects and the two buttons in the graph are listed as follows:

/// <Summary> /// this is the packaging for C functions and C ++ classes created by hosting C ++, essentially a managed Class Object // </Summary> clrclass = new clrclass (); /// <summary> /// addition /// </Summary> /// <Param name = "sender"> </param> /// <Param name =" E "> </param> private void button_aaddb_click (Object sender, eventargs e) {int A = convert. toint32 (textbox_a.text); int B = convert. toint32 (textbox_ B .text); // The addition textbox_answer.text = clrclass is implemented by calling the C function int add (int A, int B) by hosting C ++. menberfuncadd (A, B ). tostring ();} /// <summary> /// subtraction // </Summary> /// <Param name = "sender"> </param> /// <Param name =" E "> </param> private void button_asubb_click (Object sender, eventargs e) {int A = convert. toint32 (textbox_a.text); int B = convert. toint32 (textbox_ B .text); // textbox_answer.text = clrclass, which is implemented by hosting C ++ to call C ++'s cclassnative class function. menderfuncsub (A, B ). tostring ();}

This is the running effect:

 

The above is just a simple example. In fact, the hosted C ++ package can be any local C ++ code, including the MFC Library (this is my experiment ).

In the preceding example, the development environment is vs2010 and Windows is the flagship version of Windows 7.

 

Related Article

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.