检查 P/Invoke 是否成功
Check if P/Invoke was successful
我正在尝试使用 Ubuntu 14.04 在 Mono 上使用 P/Invoke 方法:
C++ 部分:
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
EXTERN_DLL_EXPORT int SomeMethod(int num);
// and .cpp file with the actual implementation
C# 部分:
[DllImport(@"TestProj")]
extern static int SomeMethod(int n);
Console.WriteLine(SomeMethod(2));
但是,如果我尝试调用该方法,我总是会得到 NullReferenceException
,我想知道如何才能确定是否因为 P/Invoke 失败而引发了异常,也许是因为它不是能够正确加载方法,或者空引用实际出现在 SomeMethod
.
中
谢谢
如果未找到共享(本机)库,您会收到:
XXXXX failed to initialize, the exception is: System.DllNotFoundException
如果您的入口点不匹配,您将收到:
XXXXX failed to initialize, the exception is: System.EntryPointNotFoundException
如果共享库崩溃,您将永远无法获得框架空引用。
所以,正在加载 .so 并正在调用 'c' 函数,但是 mono 框架中的某些东西不合适。编组互操作是我首先要看的地方。您从 C# 传递到 Cpp 或返回的内容之间存在一些不匹配...如果您提供的样本是真实的,只是 'int',而不是 pointers/structs/etc.. 那么它应该可以正常工作。
我可以创建的最简单的 Interop 案例 HelloWorld,给它一个 true 看看会发生什么:
cat countbyone.cpp
extern "C" int SomeMethod(int num) {
return num++;
}
gcc -g -shared -fPIC countbyone.cpp -o libcountbyone.so
- 或OS-X:
clang -dynamiclib countbyone.cpp -o libcoutbyone.dylib
cat interop.cs
using System;
using System.Runtime.InteropServices;
namespace InteropDemo
{
class MainClass
{
[DllImport("countbyone")]
private static extern int SomeMethod(int num);
public static void Main (string[] args)
{
var x = SomeMethod(0);
Console.WriteLine(x);
}
}
}
mcs interop.cs
mono interop.exe
应该是 1 并且没有错误...
我正在尝试使用 Ubuntu 14.04 在 Mono 上使用 P/Invoke 方法:
C++ 部分:
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
EXTERN_DLL_EXPORT int SomeMethod(int num);
// and .cpp file with the actual implementation
C# 部分:
[DllImport(@"TestProj")]
extern static int SomeMethod(int n);
Console.WriteLine(SomeMethod(2));
但是,如果我尝试调用该方法,我总是会得到 NullReferenceException
,我想知道如何才能确定是否因为 P/Invoke 失败而引发了异常,也许是因为它不是能够正确加载方法,或者空引用实际出现在 SomeMethod
.
谢谢
如果未找到共享(本机)库,您会收到:
XXXXX failed to initialize, the exception is: System.DllNotFoundException
如果您的入口点不匹配,您将收到:
XXXXX failed to initialize, the exception is: System.EntryPointNotFoundException
如果共享库崩溃,您将永远无法获得框架空引用。
所以,正在加载 .so 并正在调用 'c' 函数,但是 mono 框架中的某些东西不合适。编组互操作是我首先要看的地方。您从 C# 传递到 Cpp 或返回的内容之间存在一些不匹配...如果您提供的样本是真实的,只是 'int',而不是 pointers/structs/etc.. 那么它应该可以正常工作。
我可以创建的最简单的 Interop 案例 HelloWorld,给它一个 true 看看会发生什么:
cat countbyone.cpp
extern "C" int SomeMethod(int num) {
return num++;
}
gcc -g -shared -fPIC countbyone.cpp -o libcountbyone.so
- 或OS-X:
clang -dynamiclib countbyone.cpp -o libcoutbyone.dylib
cat interop.cs
using System;
using System.Runtime.InteropServices;
namespace InteropDemo
{
class MainClass
{
[DllImport("countbyone")]
private static extern int SomeMethod(int num);
public static void Main (string[] args)
{
var x = SomeMethod(0);
Console.WriteLine(x);
}
}
}
mcs interop.cs
mono interop.exe
应该是 1 并且没有错误...