如何将c++代码添加到Unity项目中
How to add c++ code to Unity project easy-way?
所以,我试图在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);
}
}
引用:
- https://docs.unity3d.com/Manual/NativePlugins.html
- http://www.mono-project.com/docs/advanced/pinvoke/
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 无法在 CLion 中构建 C++ 项目
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 欧拉项目#8答案是大以获得有效答案
- 从链接列表c++中删除一个项目
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 既然存在危险,为什么项目要使用-I include开关
- cmake在我的项目中所需的所有静态库都不成功
- QT通过C++添加映射QML项目
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 在linux上调试巨大的C++项目
- 在其他文件中创建类时在 c++ 项目中不起作用
- Unity在虚幻引擎4中的"Vector3.Slerp"等效C++?
- Unity webGL - MacOS 上的构建项目失败
- 如何将c++代码添加到Unity项目中
- IOS集成Unity 4.6.3项目(64位&&IL2CPP)。出现以下这样的错误,如何解决?
- 在Unity项目中使用依赖于另一个NDK构建的库时出错
- 通过类库访问Unity IL2CPP项目中的Windows 10函数