C DllImport用法和路徑問題

2022-08-23 10:03:11 字數 1889 閱讀 3496

dllimport是system.runtime.interopservices命名空間下的乙個屬性類,其功能是提供從非託管dll匯出的函式的必要呼叫資訊。

dllimport屬性應用於方法,要求最少要提供包含入口點的dll的名稱。

dllimport的定義如下:

[attributeusage(attributetargets.method)]

public class dllimportattribute: system.attribute

//定位引數為dllname

public callingconvention callingconvention; //入口點呼叫約定

public charset charset; //入口點採用的字元接

public string entrypoint; //入口點名稱

public bool exactspelling; //是否必須與指示的入口點拼寫完全一致,預設false

public bool preservesig; //方法的簽名是被保留還是被轉換

public bool setlasterror; //findlasterror方法的返回值儲存在這裡

public string value }

} 用法示例:

[dllimport("kernel32")]

private static extern long writeprivateprofilestring(string section,string key,string val,string filepath);

以上是用來寫入ini檔案的乙個win32api。

用此方式呼叫win32api的資料型別對應:dword=int或uint,bool=bool,預定義常量=enum,結構=struct。

[dllimport("kernel32.dll")]

private extern static intptr loadlibrary(string path);

[dllimport("kernel32.dll")]

private extern static intptr getprocaddress(intptr lib, string funcname);

[dllimport("kernel32.dll")]

private extern static bool freelibrary(intptr lib);

分別取得了loadlibrary和getprocaddress函式的位址,再通過這兩個函式來取得我們的dll裡面的函式。

以下自定義類的**完成loadlibrary的裝載和函式呼叫:

public class dllinvoke

~dllinvoke()

//將要執行的函式轉換為委託

public delegate invoke(string apiname,type t)

}下面**進行呼叫

public delegate int compile(string command, stringbuilder inf);

//編譯

compile compile = (compile)dll.invoke("compile", typeof(compile));

stringbuilder inf;

compile(@「gcc a.c -o a.exe「,inf);//這裡就是呼叫我的dll裡定義的compile函式

C DllImport用法和路徑問題

dllimport是system.runtime.interopservices命名空間下的乙個屬性類,其功能是提供從非託管dll匯出的函式的必要呼叫資訊。dllimport屬性應用於方法,要求最少要提供包含入口點的dll的名稱。dllimport的定義如下 attributeusage attri...

相對路徑和絕對路徑以及它們的用法

什麼是絕對定位,什麼是相對定位?1.相對引用指引用的檔案相對於,當前位置的所在位置 eg index.php 同一目錄下的index.php檔案 test index.php 同一目錄下的test資料夾下的index.php檔案 2.絕對引用,引用的是絕對位址 eg require once str...

絕對路徑與相對路徑用法

在網頁製作的過程中,少不了跟路徑打交道,比如,包含乙個檔案,插入乙個等,與路徑都有關係,如果使用了錯誤的檔案路徑,就會導致引用失效 無法瀏覽鏈結檔案,或無法顯示插入的等 初學者可能會感到困惑,下面我就詳細的介紹一下相對路徑與絕對路徑。html有2種路徑的寫法 相對路徑和絕對路徑。html相對路徑 r...