如何将c++代码添加到Unity项目中

How to add c++ code to Unity project easy-way?

本文关键字:Unity 项目 添加 代码 c++      更新时间:2023-10-16

所以,我试图在Unity中构建一个应用程序,这需要分子可视化。有一些库可以用来估计分子的性质,读分子,写分子等。但很少有视觉化的。我找到了一个叫做hyperballs的工具,它被成功地用在了一个叫做UnityMol的Unity分子可视化项目中。我已经将OpenBabel dll添加到项目中,现在我希望我可以以相同或任何其他方式添加hyperballs到unity项目中。

问题是我缺乏制作dll的经验(老实说,一点经验也没有)。

我也不知道如何在Unity项目中使用hyperballs c++文件。考虑到与OpenBabel的类比,我认为如果有一种简单的方法可以在Mac上从c++源代码制作dll,我可能只需要将dll添加到资产中并享受编码,但这并不像我想象的那么容易。

您需要将c++代码封装在C函数中,然后通过p/Invoke使用它们。

例如,

MyPlugin.cpp

#define MY_API extern "C"
class Context
{
public:
    const int version = 12345;
};
MY_API int GetVersion(const Context* _pContext)
{
    if (_pContext == nullptr)
    {
        return 0;
    }
    return _pContext->version;
}
MY_API Context* CreateContext()
{
    return new Context();
}
MY_API void DestroyContext(const Context* _pContext)
{
    if (_pContext != nullptr)
    {
        delete _pContext;
    }
}

然后将上述代码编译为Windows的*.dll, Android的*.so, iOS的Cocoa Touch Static Library和macOS的bundle

在c#中的用法:

MyPlugin.cs

using System;
using System.Runtime.InteropServices;
using UnityEngine;
public class MyAPI : MonoBehaviour
{
#if UNITY_EDITOR || UNITY_STANDALONE
    const string dllname = "MyPlugin";
#elif UNITY_IOS
    const string dllname = "__Internal";
#endif
    [DllImport(dllname, CallingConvention = CallingConvention.Cdecl)]
    private static extern IntPtr CreateContext();
    [DllImport(dllname, CallingConvention = CallingConvention.Cdecl)]
    private static extern int GetVersion(IntPtr _pContext);
    [DllImport(dllname, CallingConvention = CallingConvention.Cdecl)]
    private static extern void DestroyContext(IntPtr _pContext);
    static MyAPI()
    {
        Debug.Log("Plugin name: " + dllname);
    }
    void Start ()
    {
        var context = CreateContext();
        var version = GetVersion(context);
        Debug.LogFormat("Version: {0}", version);
        DestroyContext(context);
    }
}

引用:

  1. https://docs.unity3d.com/Manual/NativePlugins.html
  2. http://www.mono-project.com/docs/advanced/pinvoke/