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));
}
点赞鼓励下,(づ ̄3 ̄)づ╭❤~
作者:世纪末的魔术师
出处:https://www.cnblogs.com/Firepad-magic/
Unity最受欢迎插件推荐:点击查看
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。