簡體   English   中英

如何調用從C ++ dll加載的將指針作為輸入的外部函數

[英]How to call an external function that takes pointers as input, loaded from a C++ dll

我有一個C#項目,需要使用外部dll。

dll是使用C ++構建的。 我只有描述函數接口(簽名)和.dll(二進制代碼)的c ++頭文件(.hpp)。

我想在我的C#項目中動態加載dll並使用兩個函數:

void OpenService(long &handle);
int GetCode(long handle, const char* pin, char* passcode, char* nextPasscode, char* tokencode, char* nextTokencode);

我能夠使用DllImport從System.Runtime.InteropServices加載dll,並且它使用以下代碼可用於第一個功能:

[DllImport(@"C:\Program Files\Path to my dll\myDll.dll")] 
    public static extern void OpenService(ref long handle); 

但是對於第二個,我嘗試了下面的代碼:

[DllImport(@"C:\Program Files\Path to my dll\myDll.dll")] 
    unsafe public static extern int GetCode (long handle, string* pin, string* passcode, string* nextPasscode, string* tokencode, string* nextTokencode);

但是編譯器抱怨我在編譯時應該使用不安全模式才能使用C#指針,由於技術負責人強加的規則,我無法做到這一點。

所以,我的問題是如何在不使用C#指針的情況下調用第二個函數?

我試圖將引用用作波紋管:

[DllImport(@"C:\Program Files\Path to my dll\myDll.dll")] 
    public static extern int GetCode (long handle, ref string pin, ref string passcode, ref string nextPasscode, ref string tokencode, ref string nextTokencode);

但是,只要我調用GetCode,程序就會崩潰。

關於如何解決此問題的任何想法嗎?

先感謝您。

您可以使用MarshalAs方法將字符串封送(轉換)為char *類型,而不是使用不安全和指針:

[DllImport(@"C:\Program Files\Path to my dll\myDll.dll")] 
public static extern int GetCode (long handle,  [MarshalAs(UnmanagedType.LPStr)]string pin,  [MarshalAs(UnmanagedType.LPStr)]string passcode,  [MarshalAs(UnmanagedType.LPStr)]string nextPasscode,  [MarshalAs(UnmanagedType.LPStr)]string tokencode,  [MarshalAs(UnmanagedType.LPStr)]string nextTokencode);

UnmanagedType.LPStr表示該字符串將被編組為

指向以NULL終止的ANSI字符數組的指針。

如果需要unicode,可以使用UnmanagedType.LPWStr

這是更多信息:

https://docs.microsoft.com/en-us/dotnet/framework/interop/default-marshaling-for-strings

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM