Reputation: 878
So, I am trying to build an app in Unity, which requires molecular visualisation. There are some libraries which can be used to estimate properties of molecules, read molecules, write molecules etc. But there are few for visualisation. I have found this one, called hyperballs and it is used successfully in a Unity project for molecular visualisation called UnityMol. I have already added OpenBabel dll to the project now I wish I could add hyperballs the same or any other way to unity project.
The problem is that I lack experience with making dlls (no experience at all, to be honest).
Also I don't know how to use hyperballs c++ files inside the Unity project. Thinking of an analogy with OpenBabel I thought that if there is a simple way to make a dll from c++ source code on a Mac, I could probably simply add dll to assets and enjoy coding, but it is not as easy, as I thought.
Upvotes: 4
Views: 6095
Reputation: 4889
You need to wrap the C++ code in C functions, then use them through P/Invoke.
For example,
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;
}
}
Then compile the above code into *.dll
for Windows, *.so
for Android, Cocoa Touch Static Library
for iOS and bundle
for macOS.
Usage in 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);
}
}
References:
Upvotes: 8