![](/img/trans.png)
[英]P/Invoking unmanaged C++ code from c# - Getting a “tried to access protected memory error”
[英]Can't handle exceptions when invoking C# function from unmanaged C++ code
The idea of issue is following: I'm passing C# function pointer to C++ compiled library then from C++ invoke passed function. 我想從代碼中捕獲 C#/C++ 異常,該異常位於 C++ function 調用之前。
The idea of issue is following: I'm passing C# function pointer to C++ compiled library then from C++ invoke passed function. 我的 C++ 調用包含在try/catch
中,我想從 C++/C# 函數中捕獲異常。
所以,我有 .NET 5 應用程序,它運行以下代碼:
class NetProgram
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void CustomCppFunc(int id);
[DllImport("/root/projects/LinuxLoop/bin/x64/Debug/libLinuxLoop.so")]
protected static extern void strg_Create(IntPtr cb_is_my);
static void Main(string[] args)
{
CustomCppFunc sharpDelegate = new CustomCppFunc(Smth.sharpStaticMethod);
try
{
strg_Create(Marshal.GetFunctionPointerForDelegate(sharpDelegate));
}
catch (Exception e)
{
Console.WriteLine("Catched exception from C# Program: " + e.Message);
}
finally
{
Console.WriteLine("Finally from C# Program.");
}
}
public class Smth
{
public static void sharpStaticMethod(IntPtr id)
{
Console.WriteLine("C#. sharpStaticMethod. Invoked.");
Console.WriteLine("C#. sharpStaticMethod. Zero division.");
var b = 0;
var a = 1 / b;
}
}
}
libLinuxLoop.so 是 Linux 的 C++ 編譯庫(我使用的是 CentOS 7),它具有以下內容:
MyCppFunc.h:
#ifdef MYCPPFUNC
#define MYCPPFUNC __attribute__((dllexport))
#else
#define MYCPPFUNC __attribute__((dllimport))
#endif
typedef void(*CBIsMy)(int order_id);
extern "C" MYCPPFUNC void *strg_Create(CBIsMy cb_is_my);
MyCppFunc.cpp:
#include <cstdio>
#include <utility>
#include <limits.h>
#include "MyCppFunc.h"
void *strg_Create(CBIsMy cb_is_my) {
std::fputs("C++. strg_Create. Invoked.\n", stdout);
std::fputs("C++. strg_Create. Invoking C# delegate.\n", stdout);
cb_is_my(1);
return NULL;
}
運行應用程序會寫入以下消息:
C++. strg_Create. Invoked.
C++. strg_Create. Invoking C# delegate.
C#. sharpStaticMethod. Invoked.
C#. sharpStaticMethod. Zero division.
Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
at TestPlayground0806.NetProgram.Smth.sharpStaticMethod(Int32 id) in C:\Users\dev02\source\repos\TestPlayground0806\TestPlayground0806\NetProgram.cs:line 106
Aborted (core dumped)
結果:由非托管代碼調用的 C# function 引發異常,導致整個應用程序崩潰。 為了捕捉這些異常,我應該怎么做?
UPD:在 Windows 10 上捕獲了異常,但我在 CentOS 7 上無法捕獲它。
它在 Windows 上以這種方式工作,因為 Windows 堆棧幀通過非托管幀支持異常機制。 它在 Linux 上不起作用,因為 Linux 堆棧幀不支持通過非托管幀的異常機制。 – 艾爾傑
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.