互操作性C# 调用 C++生成的DLL

C++创建的是Win32 DLL程序,代码如下:

#include "stdafx.h"
#include "CustomerInfo.h"
#include <stdio.h>
#include <malloc.h>

typedef struct{
	char name[32];
	int age;
}Customer;


CustomerInfo* customerInfo;

extern "C" __declspec(dllexport) Customer* Create(char* name, int age)
{
	Customer* cust = (Customer*)malloc(sizeof(Customer));

	customerInfo = new CustomerInfo(name, age);
	strcpy(cust->name,customerInfo->GetName());
	cust->age = customerInfo->GetAge();

	return cust;
}

void __stdcall PrintMsg(const char* msg)
{
	printf("%s\n",msg);
	return;
}

extern "C" __declspec(dllexport) int Add(int x, int y)
{
	return x + y;
}

extern "C" __declspec(dllexport) int Sub(int x, int y)
{
	return x - y;
}

C++创建的头文件CustomerInfo.h代码如下:

class CustomerInfo{
private:
	char* m_Name;
	int m_Age;

public:
	CustomerInfo(char* name, int age)
	{
		m_Name = name;
		m_Age = age;
	}

	virtual ~CustomerInfo(){}
	int GetAge(){ return m_Age;}
	char* GetName() { return m_Name;}
};

C#创建控制台应用程序,代码如下:

   class Program
    {
        [DllImport("NativeLibTest.dll")]
        public static extern int Add(int x, int y);

        [DllImport("NativeLibTest.dll")]
        public static extern int Sub(int x, int y);

        [DllImport("NativeLibTest.dll")]
        public static extern IntPtr Create(string name, int age);


        [StructLayout(LayoutKind.Sequential)]
        public struct Customer
        {
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
            public string Name;

            public int Age;
        }


        static void Main(string[] args)
        {
           int temp = Add(4, 7);
           Console.WriteLine( temp.ToString());

           IntPtr ptr = Create("work hard work smart", 27);
           Customer customer = (Customer)Marshal.PtrToStructure(ptr, typeof(Customer));
           Console.WriteLine("Name:{0}, Age:{1}", customer.Name, customer.Age);
        }
    }

注意:C++生成的DLL和Lib文件拷到C#的Bin目录下,或者输出文件路径指向为生成的DLL文件路径。

原文地址:https://www.cnblogs.com/linlf03/p/2189396.html