unity3d和c++相互调用(windows平台)

//新建项目-window桌面向导,建立一个C++ DLL库文件空项目,



#ifndef _CPP_Test_H_
#define _CPP_Test_H_

#include <string>

#ifdef _WIN32
//_declspec(dllexport)只在windows下使用
#define EXPORT_DLL  _declspec(dllexport)
#else 
#define EXPORT_DLL

#endif


extern "C"
{
	
	int ai = 0;
	typedef char*(*CallBack)(const char* str);
	CallBack  FunA;

	EXPORT_DLL void SetIntA(int a)
	{
		ai = a;
	}

	EXPORT_DLL int GetIntA()
	{
		return ai;
	}


	EXPORT_DLL int addNumber(int a, int b) {
		return a + b;
	}


	EXPORT_DLL void SetCallBack(CallBack a)
	{
		FunA = a;
	}

	//EXPORT_DLL const char* CallFun(const char* ch)
	//{
	//	return  FunA(ch);
	//}


	EXPORT_DLL const char* CallFun( const char* ch )
	{

		char *buff1 = FunA(ch);

		std::string str = "CPPInner ";
		str += buff1;

		return  str.c_str(); //FunA(ch);
	}

	EXPORT_DLL const char* SayHelloWorld() {
		return "hello world";
	}



};
#endif

 //根据电脑平台,x64还是x84 ,生成 dll文件,然后导入uniyt的plugins/x64文件下。

 

 

using AOT;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using System.Text;

public class CallTest : MonoBehaviour {

	[DllImport("ExportToUnity1")]
	private extern static int addNumber(int a, int b);

	[DllImport("ExportToUnity1")]
	private extern static void SetIntA(int a);

	[DllImport("ExportToUnity1")]
	private extern static int GetIntA();


	//--------------

	//C++ 调用C#
	public delegate string CallBack(string s);

	[DllImport("ExportToUnity1")]
	private extern static string SetCallBack(CallBack a);


	[DllImport("ExportToUnity1")]
	private extern static IntPtr CallFun(string a);

	//-------------


	[DllImport("ExportToUnity1")]
	public static extern IntPtr SayHelloWorld();



	// Use this for initialization
	void Start () {

		print(addNumber(1, 2));
		SetIntA(10);
		print(GetIntA());


		SetCallBack(CallBackFun1);
		print("-----------");

		IntPtr ret0 = CallFun("abc");
		string str0 = Marshal.PtrToStringAnsi(ret0);

		print(str0);

		print("-----------");
		IntPtr ret = SayHelloWorld();
		string str = Marshal.PtrToStringAnsi(ret);
		print(str);

	}

	//回调函数
	[MonoPInvokeCallback(typeof(CallBack))]
	public string CallBackFun1(string s) //加static 可以兼容所有模式
	{
		Debug.Log("debug:"+s);

		s +=  " Csharp";

		return s;
	}



}

 

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值