How to call C ++ C #

In her spare time, remember what notes! Record about c # how to call C ++ dynamic library (dll).

step:

First, create a C ++ class, such as:


AddOperate.h

extern _declspec(dllexport) int Sum(int a, int b);
class AddOperate
{
public :
};

AddOperate.cpp

#include "AddOperate.h"
#include "iostream"
using namespace std;

int Sum(int a, int b)
{
    if (a - (int)a != 0 || b - (int)b != 0) {
        cout << "请输入整数" << endl;
        return -1;
    }
    return a + b;
}

2, the C ++ code compiled DLL dll
need to compile the configuration settings:
A: Project - Attribute Type --- compensation index - General Configuration Type --- --- dynamic libraries (.dll)

 

 

 B: Project - Properties - Configuration Properties --C / C ++ --- Advanced --- --- thinking that is compiled into C ++ code (/ TP)

 

 

 X64 attention to this event, call put the best C # also use the X64;

Then click on the project - generated, you will see a dll;

3, the c # dll copied to the directory entry input, generally in bin / debug below;

4, written in C # code calls dll

 [DllImport("Calculate.dll", CallingConvention = CallingConvention.Cdecl)]
        extern static int Sum(int a, int b);
        public static void Main(string[] args) {
            try {
                Console.WriteLine("请输入NumberA:");
                int numberA = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("请输入NumberB:");
                int numberB = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine($"the numberA is:{numberA};numberB is:{numberB},The Sum is:{Sum(numberA, numberB)}");
               
            }
            catch(Exception ex) {
                Console.WriteLine($"ex:{ex}");
            }

            Console.ReadLine();
        }

The two main lines:

 

 

 

The "Sum" method must be the same with dll method name, or can not find;

Then look at the results:

Very embarrassing, suggesting no "Sum" method, do we have operating problems.

When the investigation for a long time, to find ways to compile C ++ dll, method name will change, but also for safety;

solution:

Take C ++ code into C language!

 

 In this way, then compile dll come, execute again:

Results:

 

V. Other issues that may be encountered

A: call to PInvoke function causes a stack asymmetry

  Define the method: CallingConvention = CallingConvention.Cdecl

B: Untreated System.BadImageFormatException, trying to load program with an incorrect format. (Exception from HRESULT: 0x8007000B)

 

 

So OK! .

 

Guess you like

Origin www.cnblogs.com/skyfreedom/p/11773597.html