How do I correctly wrap native c library in Xamarin.iOS

微笑、不失礼 提交于 2020-01-02 07:29:30

问题


I am trying to bind a native c (not objective c) library to Xamarin.iOS.

My project that consists of .c and .h files is building fine in XCode. Actual .h and .m of the project do not contain any functions, I only need to use the c-defined routines.

The h file, that contains the required method definition looks like this:

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

int sprec_flac_encode(const char *wavfile, const char *flacfile);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* !__SPREC_FLAC_ENCODER_H__ */

I've build it into a fat binary, but the specification in Xamarin Documentation is not clear. Given I am binding a native library, do I need a Binding project in my solution. Anyway I need a wrapper call to put my DLLImport definitions in? Where is this process documented? I need a tutorial for my particular situation.

P.S. Objective Sharpie is generating an empty binding class if I "feed" it my .h file, probably since it is not objective-c.


回答1:


Since it is C code you should use something like PInvoke Interop Assistant to generate the C# bindings.

public partial class NativeMethods 
{
    [DllImport("<libnamehere>", 
        EntryPoint="sprec_flac_encode", 
        CallingConvention = CallingConvention.Cdecl)]
    public static extern int FlacEncode(
        [MarshalAs(UnmanagedType.LPStr)] string wavfile, 
        [MarshalAs(UnmanagedType.LPStr)] string flacfile) ;

}

No ObjectiveC binding project is needed for C libraries. Just build the native lib and add it to your project with the Dll imports.



来源:https://stackoverflow.com/questions/24634880/how-do-i-correctly-wrap-native-c-library-in-xamarin-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!