c++本地动态连接库代码
1 #pragma once 2 #include "stdafx.h" 3 4 #ifdef PERSON_EXPORTS 5 #define PERSON_API __declspec(dllexport) 6 #else 7 #define PERSON_API __declspec(dllimport) 8 #endif 9 10 class PERSON_API CPerson 11 { 12 public: 13 CPerson(LPCTSTR pszName, SYSTEMTIME birth); 14 unsigned int getAge(void); 15 16 private: 17 TCHAR _name[256]; 18 SYSTEMTIME _birth; 19 }; 20 21 #ifdef __cplusplus 22 extern "C"{ 23 #endif 24 extern PERSON_API int nVal; 25 PERSON_API int nFunc(void); 26 #ifdef __cplusplus 27 } 28 #endif
Source
1 // CPerson.cpp: 定义 DLL 应用程序的导出函数。 2 // 3 4 #include "stdafx.h" 5 #include "CPerson.h" 6 7 CPerson::CPerson(LPCTSTR pszName, SYSTEMTIME birth) 8 { 9 _birth = birth; 10 if (pszName != nullptr) 11 lstrcpy(_name, pszName); 12 } 13 14 unsigned int CPerson::getAge(void) 15 { 16 SYSTEMTIME st; 17 GetSystemTime(&st); 18 UINT age = st.wYear - _birth.wYear; 19 if (_birth.wMonth > st.wMonth || 20 (_birth.wMonth == st.wMonth && _birth.wDay > st.wDay)) 21 { 22 --age; 23 } 24 25 return age; 26 } 27 28 PERSON_API int nVal = 20180403; 29 PERSON_API int nFunc(void) 30 { 31 return 1816; 32 }
c++/cli包装代码
1 #pragma once 2 #include "CPerson.h" 3 4 using namespace System; 5 6 namespace Adapter 7 { 8 public ref class Person 9 { 10 public: 11 Person(String ^name, DateTime birth); 12 virtual ~Person(); 13 14 property unsigned int Age 15 { 16 unsigned int get(); 17 } 18 19 static int CallnVal(); 20 static int CallnFunc(); 21 22 private: 23 Person(): _person(nullptr) { } 24 CPerson *_person; 25 }; 26 }
Source
1 #include "stdafx.h" 2 #include "Person.h" 3 #include <vcclr.h> 4 5 Adapter::Person::Person(String ^ name, DateTime birth) 6 { 7 SYSTEMTIME st = { 0 }; 8 st.wYear = birth.Year; 9 st.wMonth = birth.Month; 10 st.wDay = birth.Day; 11 12 pin_ptr<const TCHAR> psz = PtrToStringChars(name); 13 14 _person = new CPerson(psz, st); 15 } 16 17 Adapter::Person::~Person() 18 { 19 //System::Diagnostics::Debugger::Log(0, "Debug", "Person destructor."); 20 if (_person != nullptr) 21 { 22 CPerson *ptmp = _person; 23 _person = nullptr; 24 delete ptmp; 25 } 26 } 27 28 int Adapter::Person::CallnVal() 29 { 30 return nVal; 31 } 32 33 int Adapter::Person::CallnFunc() 34 { 35 return nFunc(); 36 } 37 38 unsigned int Adapter::Person::Age::get() 39 { 40 return _person->getAge(); 41 }
经过验证使用Visual Studio 2017包含头文件<vcclr.h>会有报错,可以设置修改平台工具集来编译
通过CSharp调用
1 using System; 2 using Adapter; 3 4 namespace ConsoleApp 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 { 10 DateTime dt = DateTime.Now; 11 dt = dt.AddYears(-50); 12 Person p1 = new Person("c++", dt); 13 Console.WriteLine("调用本地c++ dll中的类: " + p1.Age); 14 Console.WriteLine("调用本地c++ dll中的变量: " + Person.CallnVal()); 15 Console.WriteLine("调用本地c++ dll中的函数: " + Person.CallnFunc()); 16 17 Console.ReadLine(); 18 } 19 } 20 }
参考资料详情:
https://www.codeproject.com/Articles/35041/Mixing-NET-and-native-code
https://blog.csdn.net/ganzheyu/article/details/50154705