Unity中 Plugin 跨语言 类型转换

Unity 支持Plugin ,有一些代码我们可以用C++ 来编写成 Plugin 供C#调用,,但是对于不同语言之间的类型转换就会很纠结。比如说 C# 里面的 string 到C++ 里面是什么?C++里面的string到C#里面是什么?

引自Unity官方的例子

C++咯平台代码如下:

Win32/64

#if _MSC_VER // this is defined when compiling with Visual Studio#define EXPORT_API __declspec(dllexport) // Visual Studio needs annotating exported functions with this#else#define EXPORT_API // XCode does not need annotating exported functions, so define is empty#endif// ————————————————————————// Plugin itself// Link following functions C-style (required for plugins)extern "C"{// The functions we will call from Unity.//const EXPORT_API char* PrintHello(){return "Hello";}int EXPORT_API PrintANumber(){return 5;}int EXPORT_API AddTwoIntegers(int a, int b) {return a + b;}float EXPORT_API AddTwoFloats(float a, float b) {return a + b;}} // end of export C block

Android

/*This is a simple plugin, a bunch of functions that do simple things.*/extern "C" {const char* PrintHello(){return "Hello";}int PrintANumber(){return 5;}int AddTwoIntegers(int a, int b) {return a + b;}float AddTwoFloats(float a, float b) {return a + b;}}

MAC/IOS

extern "C" {const char* PrintHello ();int PrintANumber ();int AddTwoIntegers(int, int);float AddTwoFloats(float, float);}/*This is a simple plugin, a bunch of functions that do simple things.*/#include "Plugin.pch"const char* PrintHello(){return "Hello";}int PrintANumber(){return 5;}int AddTwoIntegers(int a, int b) {return a + b;}float AddTwoFloats(float a, float b) {return a + b;}

C#调用代码

using UnityEngine;using System.Collections;using System;using System.Runtime.InteropServices;public class PluginImport : MonoBehaviour {//Lets make our calls from the Plugin[DllImport ("ASimplePlugin")]private static extern int PrintANumber();[DllImport ("ASimplePlugin")]private static extern IntPtr PrintHello();[DllImport ("ASimplePlugin")]private static extern int AddTwoIntegers(int i1,int i2);[DllImport ("ASimplePlugin")]private static extern float AddTwoFloats(float f1,float f2);void Start () {Debug.Log(PrintANumber());Debug.Log(Marshal.PtrToStringAuto (PrintHello()));Debug.Log(AddTwoIntegers(2,2));Debug.Log(AddTwoFloats(2.5F,4F));}}

在Unity3d Doc中提到,托管与非托管之间的类型转换可以参照 MSDN中的文档。

https://msdn.microsoft.com/en-us/library/fzhhdwae.aspxNative Library的使用方法参照 Mono的文档

上面两个网页文档很详细的介绍了Native Library使用以及托管与非托管之间的转换。

业精于勤,荒于嬉;行成于思,毁于随。

Unity中 Plugin 跨语言 类型转换

相关文章:

你感兴趣的文章:

标签云: