在c# Unity3d中添加静态c++库

DllImport static C++ library in C# Unity3d

本文关键字:静态 c++ 添加 Unity3d      更新时间:2023-10-16

对于函数的简单签名,只需:

    [DllImport("__Internal")]
public static extern MyFunc(int a);

如何实现

的功能
static App* Create(const AppOptions& options, JNIEnv* jni_env,
                 jobject activity);

c++中的指针和引用如何替换为c# ?

您需要使用封送处理。

例子:

/* unmanaged code declarations */
 struct UnmanagedStruct {
    int n;
 };
 void PassByValue (struct UnmanagedStruct s);
 void PassByReferenceIn (struct UnmanagedStruct *s);
 void PassByReferenceOut (struct UnmanagedStruct *s);
 void PassByReferenceInOut (struct UnmanagedStruct *s);
 struct UnmanagedStruct ReturnByValue ();
 struct UnmanagedStruct* ReturnByReference ();
 void DoubleIndirection (struct UnmanagedStruct **s);

类包装器可以是:

/* note: sequential layout */
 [StructLayout (LayoutKind.Sequential)]
 class ClassWrapper {
    public int n;
    /* cannot wrap function PassByValue */
    /* PassByReferenceIn */
    [DllImport ("mylib")]
    public static extern
       void PassByReferenceIn (ClassWrapper s);
    /* PassByReferenceOut */
    [DllImport ("mylib")]
    public static extern
       void PassByReferenceOut ([Out] ClassWrapper s);
    /* PassByReferenceInOut */
    [DllImport ("mylib")]
    public static extern
       void PassByReferenceInOut ([In, Out] ClassWrapper s);
    /* cannot wrap function ReturnByValue */
    /* ReturnByReference */
    [DllImport ("mylib")]
    public static extern ClassWrapper ReturnByReference ();
       /* note: this causes returned pointer to be freed
          by runtime */
     /* DoubleIndirection */
    [DllImport ("mylib")]
    public static extern
       void DoubeIndirection (ref ClassWrapper s);
 }

下面是一些有用的链接:

  1. 与本地库互操作
  2. c#的封送处理
  3. 对象默认封送