码迷,mamicode.com
首页 > 编程语言 > 详细

Unity中 Plugin 跨语言 类型转换

时间:2015-06-14 13:50:18      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:unity3d   win32   plugins   xcode   library   

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.aspx

Native Library的使用方法参照 Mono的文档

http://www.mono-project.com/docs/advanced/pinvoke/

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

Unity中 Plugin 跨语言 类型转换

标签:unity3d   win32   plugins   xcode   library   

原文地址:http://blog.csdn.net/huutu/article/details/46490339

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!