C# 调用C++ dll

参考:http://www.soaspx.com/dotnet/csharp/csharp_20110406_7469.html

测试代码:

CppDll.cs
using System;

using System.Runtime.InteropServices;



namespace CsharpDemo

{

    class CppDll

    {

        //传入int 型

        [DllImport("CsharpInvokeCpp.dll")]

        public static extern int Add(int x, int y);



        [DllImport("CsharpInvokeCpp.dll")]

        public static extern int Sub(int x, int y);



        //x,y的值使用后将改变

        [DllImport("CsharpInvokeCpp.dll")]

        public static extern int SumEditor(ref int x, ref int y);



        //DLL 需传入char* 类型 

        [DllImport("CsharpInvokeCpp.dll")]

        public static extern int CharRef(string a, string b);





        // 返回对象

        [DllImport("CsharpInvokeCpp.dll")]

        public static extern IntPtr Create(string name, int age);



        [StructLayout(LayoutKind.Sequential)]

        public struct User

        {

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]

            public string Name;



            public int Age;

        }



    }

}

 

using System;

using System.Runtime.InteropServices;



namespace CsharpDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            int result = CppDll.Add(4, 33);

            Console.WriteLine(result.ToString());



            int a = 10;

            int b = 5;

            Console.WriteLine(CppDll.SumEditor(ref a,ref b));

            Console.WriteLine(a.ToString());



            IntPtr ptr = CppDll.Create("李平", 27);



            CppDll.User user = (CppDll.User)Marshal.PtrToStructure(ptr, typeof(CppDll.User));



            Console.WriteLine(user.Name);



            Console.ReadLine();



        }

    }

}

 

CsharpInvokeCpp.cpp
// CsharpInvokeCpp.cpp : 定义 DLL 应用程序的导出函数。

//



#include "stdafx.h"

#include "malloc.h"

#include "userinfo.h"





extern "C" __declspec(dllexport) int __stdcall    Add(int x,int y){



    return  x+y;



}



extern "C" __declspec(dllexport) int __stdcall  Sub(int x,int y){



    return  x-y;



}



extern "C" __declspec(dllexport) int __stdcall  SumEditor(int *x ,int *y){

    *x=100;

    *y=50;

    return  *x + *y;

}



extern "C" __declspec(dllexport) int __stdcall  CharRef(char* a,char* b){



    return  1;

}



typedef struct {

    char name[32];

    int age;

}User;



UserInfo* userInfo;



extern "C" __declspec(dllexport) User*  __stdcall Create(char* name, int age)    

{   

   User* user = (User*)malloc(sizeof(User));

   userInfo = new UserInfo(name, age);

   strcpy(user->name, userInfo->GetName());  

   user->age = userInfo->GetAge();

   return user; 

}
UserInfo.cpp
#include "StdAfx.h"

#include "UserInfo.h"





UserInfo::UserInfo(char* name, int age)

{

    m_Name = name; 

    m_Age = age;

}





UserInfo::~UserInfo(void)

{

}





int UserInfo::GetAge()

{ 

    return m_Age; 

}

char* UserInfo::GetName()

{ 

    return m_Name; 

}

你可能感兴趣的:(C++)