# C++與Unity C#交互

C++與Unity C#交互

C++轉C#小工具:https://github.com/jaredpar/pinvoke-interop-assistant

C++

Custom.h

#pragma once
#include <functional>

class __declspec(dllexport) MyCustom
{
public:
	int getAdd(int a,int b);
};

extern "C" __declspec(dllexport)int customAdd(int a,int b);

extern "C" __declspec(dllexport)int run();

typedef void (*MYCALLBACK)(int); //使用C形式函數指針
extern "C" __declspec(dllexport)int setcallback( MYCALLBACK func);


Custom.cpp

#include "pch.h"
#include <chrono>
#include <thread>
#include "Custom.h"

MyCustom* ct = new MyCustom;

int MyCustom::getAdd(int a, int b) { return a + b; }


int customAdd(int a, int b) {
	return ct->getAdd(a, b);
}



std::function<void(int)> Func;

int setcallback(MYCALLBACK func)
{
	Func = std::move(func);

	return 0;
}

int run()
{
	static int i = 0;

	while (i<100)
	{
		if (Func)
		{
			Func(i);
			i++;
			std::this_thread::sleep_for(std::chrono::seconds(1));
		}
	}

	return 0;
}

Unity -C#

Test.cs

    [DllImport("Dll2Unity")]
    private static extern int customAdd(int a, int b);

    [DllImport("Dll2Unity")]
    private static extern int run();

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    private delegate void MYCALLBACK(int value);

    [DllImport("Dll2Unity")]
    private static extern int setcallback(MYCALLBACK callback);
    void Start()
    {
        setcallback(x => { Debug.Log(x); });
        Task.Run(run);
        Debug.Log(customAdd(1, 2));
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章