c#調(diào)用c++的DLL的實現(xiàn)方法
C#是托管型代碼,創(chuàng)建的對象會自動回收。C++是非托管型代碼,創(chuàng)建的對象需要手動回收(有時不手動回收,可能出現(xiàn)內(nèi)存溢出的問題)。
C#調(diào)用C++的方式分為兩種:(1)采用托管的方式進行調(diào)用;(2)非托管的方式進行調(diào)用。
1.采用托管的方式進行調(diào)用,就和正常調(diào)用c#的dll一樣
創(chuàng)建新的c++項目

Function.h中的代碼,一個返回兩數(shù)之和的方法,一個返回字符串的方法
#pragma once
#include <string>
public ref class Function
{
public:
Function(void);
~Function(void);
int menber;
int menberFuncAdd(int a,int b);
System::String^ say(System::String^ str);
};
//.cpp
#include "Function.h"
Function::Function(void)
{
}
Function::~Function(void)
{
}
int Function::menberFuncAdd(int a,int b)
{
return a+b;
}
System::String^ Function::say(System::String^ str)
{
return str;
}Function.h中空白不用寫
#include "Function.h"
注意:c++的項目一定要選擇公共語言運行時支持

在c#的項目中像引用c#的dll一樣引用

代碼中調(diào)用

Function fun = new Function();
int a = fun.menberFuncAdd(1, 2);
string s = fun.say("Hello World");注意:c#項目一定要選擇x86,否則要報錯。

運行效果:

2.非托管的方式進行調(diào)用
創(chuàng)建新的c++項目

stdafx.h中的代碼
// stdafx.h : 標準系統(tǒng)包含文件的包含文件, // 或是經(jīng)常使用但不常更改的 // 特定于項目的包含文件 // #pragma once #include "targetver.h" #ifdef A_EXPORTS #define DLL_API __declspec(dllexport) #else #define DLL_API __declspec(dllimport) #endif #define WIN32_LEAN_AND_MEAN // 從 Windows 頭文件中排除極少使用的信息 // Windows 頭文件: #include <windows.h> extern "C" DLL_API void MessageBoxShow(); // TODO: 在此處引用程序需要的其他頭文件
dllmain.cpp中的代碼
#include "stdafx.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#ifdef _MANAGED
#pragma managed(push, off)
#endif
void MessageBoxShow()
{
MessageBox(NULL, TEXT("Hello World"), TEXT("In a DLL"), MB_OK);
}
#ifdef _MANAGED
#pragma managed(pop)
#endif注意:c++的項目一定要選擇公共語言運行時支持

在代碼加上
[DllImport("ll.dll")]
public extern static void MessageBoxShow();
注意:c#項目一定要選擇x86,否則要報錯。

運行結(jié)果:

到此這篇關(guān)于c#調(diào)用c++的DLL的實現(xiàn)方法的文章就介紹到這了,更多相關(guān)c#調(diào)用c++的DLL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實現(xiàn)字符串轉(zhuǎn)換成字節(jié)數(shù)組的簡單實現(xiàn)方法
這篇文章主要介紹了C#實現(xiàn)字符串轉(zhuǎn)換成字節(jié)數(shù)組的簡單實現(xiàn)方法,僅一行代碼即可搞定,非常簡單實用,需要的朋友可以參考下2015-05-05
C#結(jié)合Minio實現(xiàn)文件上傳存儲與更新
MinIO是一個開源的對象存儲服務(wù)器,專門設(shè)計用于在大規(guī)模數(shù)據(jù)存儲環(huán)境中運行,這篇文章主要為大家介紹了C#如何結(jié)合Minio實現(xiàn)文件上傳存儲與更新,需要的可以參考下2024-03-03
C#實現(xiàn)高性能寫入txt大量數(shù)據(jù)
在 C# 中高性能寫入大量數(shù)據(jù)到文本文件時,需結(jié)合 ?流式處理、內(nèi)存優(yōu)化和系統(tǒng)級技巧?,本文為大家介紹了針對超大規(guī)模數(shù)據(jù)的深度優(yōu)化方案,需要的可以參考一下2025-05-05

