work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on 2011-09-24 12:24  work hard work smart  阅读(526)  评论(0编辑  收藏  举报

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文件路径。