zoukankan      html  css  js  c++  java
  • 互操作性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文件路径。

  • 相关阅读:
    快速搭建http server
    cwmp part2 测试基础RPC
    Leetcode-5223 Queens That Can Attack the King(可以攻击国王的皇后)
    Leetcode-5222 Split a String in Balanced Strings(分割平衡字符串)
    Leetcode-5224 Dice Roll Simulation(掷骰子模拟)
    P2604-[ZJOI2010]网络扩容
    P2053-[SCOI2007]修车
    P2153-[SDOI2009]晨跑
    P2774 方格取数问题
    P2763-试题库问题
  • 原文地址:https://www.cnblogs.com/linlf03/p/2189396.html
Copyright © 2011-2022 走看看