我目前正在开发 NuGet 包,该包将使 .NET 开发人员在所有支持的平台上更容易使用特定硬件,因为目前除了 Windows 之外没有 .NET 接口。这些平台之一是 macOS。我有一个静态的 Objective-C++ 库,我设法将它包装到一个动态库 (dylib) 中,该库定义了 extern "C" 接口以防止名称修改(发生在静态库中)。我设法 P/Invoke 我需要的一切。我什至设法将一组结构复制到我的托管运行时。
我需要获取的最后一点信息是一些 NSString 对象 - 这就是我目前失败的地方。请注意,我删除了错误处理代码以保持示例简洁。我还通过运行 nm -g libmylib.dylib
Objective-C++ 标头
extern NSString *FONT_CALIBRI;
extern NSString *FONT_TIMES_NEW_ROMAN;
extern NSString *FONT_CENTURY_GOTHIC;
extern NSString *FONT_SIZE_18PT;
extern NSString *FONT_SIZE_20PT;
C# 代码
dll = Dlfcn.dlopen("libmylib.dylib", 0);
var sym = Dlfcn.dlsym(dll, "FONT_CALIBRI");
// The pointer is populated but this next call crashes in the managed code
var value = Marshal.PtrToStringAuto(sym);
Dlfcn.dlclose(dll);
C# 代码
dll = Dlfcn.dlopen("libmylib.dylib", 0);
var sym = Dlfcn.dlsym(dll, "FONT_CALIBRI");
// The pointer is populated but this next call crashes in the native code
var value = NSString.FromHandle(sym);
Dlfcn.dlclose(dll);
如果有人能指出我哪里出错了,我将不胜感激,如果您能提出解决方案,我将不胜感激。