C 呼叫 C dll,同時c 呼叫c

2021-10-04 22:28:36 字數 1728 閱讀 9279

筆者解決這兩個問題,花了很長一段時間,網上提供能正常執行的沒有找到,不過一邊東拼西湊,一邊靠朦還是解決了。先貼上**:

[dllimport(@"c:\users\administrator.sc-201901090132\desktop\opengl\dll3\release\dll3\dll3.dll",

entrypoint = "add",callingconvention = callingconvention.cdecl)] //引入dll,並設定字符集 

public static extern int add(int q,int a);

定義了個需要從c#呼叫c++函式的函式。[dllimport]第乙個引數表示我們要載入我們自定義的的c++dll檔案。entrypoint = "add",呼叫的c++函式介面,至於callingconvention = callingconvention.cdecl,這是重點!就是避免c++與c#的引數型別不一致報錯,如下:

原因可能是託管的 pinvoke 簽名與非託管的目標簽名不匹配。

請檢查 pinvoke 簽名的呼叫約定和引數與非託管的目標簽名是否匹配。」

接著看下add 函式在c++中的定義:

extern "c" _declspec(dllexport)int add(int a,int b);

int add(int a,int b)

如何編譯成dll檔案,這裡就不贅述。

上面完成了c#呼叫c++函式。下面使用c++呼叫c#

[unmanagedfunctionpointer(callingconvention.cdecl)]

public delegate void ekfrendercallback(int s);

[dllimport(@"c:\users\administrator.sc-201901090132\desktop\opengl\dll3\release\dll3\dll3.dll",

entrypoint ="ctoc",callingconvention = callingconvention.cdecl,charset = charset.ansi)] //引入dll,並設定字符集 

public static extern void ctoc(ekfrendercallback v);

定義了個**函式,public delegate void ekfrendercallback(int s);同時別忘了他上面的註解,同樣是為了避免引數型別不匹配,報出如下錯誤:

system.accessviolationexception:「嘗試讀取或寫入受保護的記憶體。這通常指示其他記憶體已損壞。」
我再看下在c++ 中的定義:

extern "c" _declspec(dllexport)void acc(int a, int b);

typedef void(*render)(int ptr);

static render reftemp;

extern "c" _declspec(dllexport) void ctoc(render p);

int add(int a,int b)

void acc(int a, int b)

extern "c" _declspec(dllexport) void ctoc(render p) ;

不難理解。

C 呼叫C Dll例程

form1.cs內容 using system using system.windows.forms using system.runtime.interopservices using system.text 申明dll中函式 dllimport kb dll.dll entrypoint inp...

C 呼叫C DLL 總結

當然在c 這樣定義之前要定義結構體,結構體的變數,函式要一樣。c 中的結構體是這樣的 struct stlencodedeviceinfo c 中的定義 structlayout layoutkind.sequential,charset charset.unicode public struct ...

編寫C 呼叫的C DLL

最近一段時間,經常遇到這些問題,前一陣子研究了一下,沒有記下來,沒想到最近研究又有些不記得了,今天把它寫下來以備忘。一般我們提供給其他語言呼叫的dll,都是用c或者c 編寫,然後封裝。我這邊也是採用的c 首先有幾個注意點 1 如果功能很簡單,或者不使用第三方庫 如mfc自帶的庫 建立乙個win32的...