gpt4 book ai didi

c# - 将 C# 与 Objective-C 混合

转载 作者:IT王子 更新时间:2023-10-29 04:13:10 25 4
gpt4 key购买 nike

我想使用更大的 C# 代码作为 Objective-C (Cocoa) 应用程序的库。

我发现了封装 Cocoa 代码的 MonoMac 项目,但我更愿意使用 Objective-C 编写的标准 Cocoa 应用程序,它可以调用封装的 C# 代码(其他方式)。

在 Windows 上,我习惯于制作 C++/CLI 项目,它包装 .NET 代码并为基于 C/C++ 的应用程序导出普通的旧 C 接口(interface)。

有没有什么简单的方法可以做到这一点?

最佳答案

显然,Mac OS 上没有 C++/CLI 这样的语言。在 Windows 上,C++/CLI 实际上编译为由运行 native 代码的 CLR 运行的托管代码;因为在 Mac OS Mono 上没有集成到系统中,所以恰恰相反。您的应用是原生的,它可以托管托管代码。

Mono 公开函数以在进程内托管 CLR 虚拟机。由于 CLR 类不直接暴露给您的 C 代码,您将能够通过类似反射的调用来调用对象的方法。

documentation on how to embed Mono into an application在官方网站上。由于您对 running .NET programs directly 不感兴趣, 你应该阅读 "Invoking Methods in the CIL Universe"部分。在 Mac OS 上,您需要从 /Library/Frameworks 文件夹链接到 Mono 框架,而不是使用 pkg-config

这确实不能代替对上述文档的实际阅读,但可以将以下内容视为预期内容的指南:

#include <glib/glib.h>
#include <mono/jit/jit.h>
#include <mono-metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>

// create an app domain
// http://en.wikipedia.org/wiki/Application_Domain
MonoDomain* domain = mono_jit_init("Domain");

// mandatory Cocoa call to show that Mono and ObjC work together
NSBundle* mainBundle = [NSBundle mainBundle];
NSString* dll = [mainBundle pathForResource:@"your-dll" ofType:@"dll"];

// load the referenced assembly in our domain
MonoAssembly* assembly = mono_domain_assembly_open(domain, [dll UTF8String]);
MonoImage* image = mono_assembly_get_image(assembly);

// find the class we want to wrap and create an uninitialized instance
MonoClass* classHandle = mono_class_from_name(image, "Name.Space", "YourClass");
MonoObject* object = mono_object_new(domain, classHandle);

// this calls the default, argument-less ctor
// for more complex constructors, you need to find the method handle and call it
// (helpful hint: constructors are internally called ".ctor", so the description
// string will look like "Name.Space.Class:.ctor()")
mono_runtime_object_init(object);

// get a method handle to whatever you like
const char* descAsString = "Name.Space.YourClass:YourMethod()";
MonoMethodDesc* description = mono_method_desc_new(descAsString);
MonoMethod* method = mono_method_desc_search_in_class(description, classHandle);

// call it
void* args[0];
mono_runtime_invoke(method, object, args, NULL);

// when you're done, shutdown the runtime by destroying the app domain
mono_jit_cleanup(domain);

如果您觉得这不是很吸引人,您可能想换个方向,正如您提到的那样,并查看 MonoMac ,它为您可能希望在 Mac 应用程序(Cocoa、CoreImage、CoreAnimation 等)中使用的大部分 API 提供 .NET 绑定(bind),并意味着创建您自己的绑定(bind)。

关于c# - 将 C# 与 Objective-C 混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5692813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com