我有以下的簽名非託管C++函數:調用從C#C++函數 - 不平衡棧
int function(char* param, int ret)
我試圖把它從C#:
unsafe delegate int MyFunc(char* param, int ret);
...
int Module = LoadLibrary("fullpathToUnamanagedDll");
IntPtr pProc = GetProcAddress(Module, "functionName");
MyFunc func = (MyFunc)System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(pProc, typeof(MyFunc));
unsafe
{
char* param = null;
int ret = 0;
int result = func(param, ret);
}
據我可以從舊的C++項目規範告訴兩個null爲param和0代表ret是該函數的有效輸入。當我嘗試調用它,它似乎工作,但在離開我得到以下錯誤:
PInvokeStackImbalance was detected
A call to PInvoke function '...::Invoke' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
我已經試過相當多的東西,我能想到關(不安全是不得已而爲之),但我無法找到以任何方式運行該功能而不會產生不平衡的堆棧。有什麼我可以嘗試嗎?
您是否必須將其作爲委託導入?一個正常的「靜態外部」聲明會更容易。 – 2010-07-22 09:00:11
@亨克Holterman:我想不是,我收到了一個同事的代碼,我認爲他有這樣做的理由。但是,我必須在運行時動態加載函數,而不必知道Dll名稱(路徑)或函數名稱。儘管如此,我在設計時也知道函數簽名。它能以不同的方式完成嗎? – 2010-07-22 10:47:22
'動態'是一個很好的理由,我認爲@leppies的答案是你必須去的地方。 – 2010-07-22 11:01:03