Is there a way to mix MonoTouch and Objective-C?

前端 未结 5 651
情歌与酒
情歌与酒 2020-12-04 22:05

I\'d like to know if there is a way to mix C# and Obj-C code in one project. Specifically, I\'d like to use Cocos2D for my UI in Obj-C and call some MonoTouch C#-Library tha

5条回答
  •  没有蜡笔的小新
    2020-12-04 22:55

    Re: unknown (google):

    We actually did this as described.

    See this page for a quick start, but the last code segment on that page is wrong, because it's omitting the "--xcode"-parameter. http://monotouch.net/Documentation/XCode

    What you have to do to embed your Mono-EXE/DLL into an Objective-C program is to compile your source with SharpDevelop, then run mtouch with these parameters:

    /Developer/MonoTouch/usr/bin/mtouch --linksdkonly --xcode=output_dir MyMonoAssembly.exe
    

    This only works with the full version of MonoTouch. The trial does not allow to use the "--xcode"-argument . The "--linksdkonly"-argument is needed if you want mtouch to keep unreferenced classes in the compiled output, otherwise it strips unused code.

    Then mtouch compiles your assembly into native ARM-code (file extension .s) and also generates a XCode template which loads the Mono-Runtime and your code inside the XCode/ObjC-program. You can now use this template right away and include your Obj-C-code or extract the runtime loading code from the "main.m"-file and insert it into your existing XCode-project. If you use an existing project you also have to copy all .exe/.dll/.s files from the xcode-output-dir that mtouch made.

    Now you have your Mono-Runtime and assembly loaded in an XCode-project. To communicate with your assembly, you have to use the Mono-Embedding-API (not part of MonoTouch, but Mono). These are C-style API calls. For a good introduction see this page.

    Also the Mono-Embedding-API documentation might be helpful.

    What you have to do now in your Obj-C-code is to make Embedding-API calls. These steps might involve: Get the application domain, get the assembly, get the image of the assembly, locate the class you want to use, instantiate an object from that class, find methods in class, call methods on object, encapsulate method arguments in C-arrays and pass them to the method-call, get and extract method return values. There are examples for this on the embedding-api-doc-page above.

    You just have to be careful with memory consumption of your library, as the mono runtime takes some memory as well.

    So this is the way from Obj-C to C#. If you want to make calls from C#/Mono into your Obj-C-program, you have to use the MonoTouch-bindings, which are described here.

    You could also use pure C-method calls from the embedding/P/Invoke-API.

    Hope this gets you started.

提交回复
热议问题