我试图找到一种将参数从objc / swift中的本机unity插件传递给C#unity的好方法。
似乎我将需要使用Marshall,但我在任何地方都找不到很好的例子。
我发现的唯一一件事是UnitySendMessage,但是它仅将字符串作为参数传递,甚至那些字符串被限制为1024个字节,这对于对象的JSON表示来说还是不够的,处理多个消息似乎有点过度杀伤力。
这个想法是为了能够从MTLTexture询问插件以进行对象检测,并返回被识别的对象。
代码示例:
SwiftBridge
import Foundation
import UIKit
import Vision
@objc public class SwiftBridge: NSObject {
var delegate: DelegateCallbackFunction?
@objc static let shared = SwiftBridge()
@objc func evaluate(texture: MTLTexture) -> Bool {
guard let delegate = self.delegate else {
return false
}
let rect = CGRect(x: 1, y: 2, width: 100, height: 200)
delegate(rect)
return true
}
@objc func setDelegate(callback: @escaping DelegateCallbackFunction) -> Bool {
self.delegate = callback
return true
}
}
团结
using System;
using UnityEngine;
using System.Runtime.InteropServices;
using AOT;
[StructLayout(LayoutKind.Sequential)]
public struct CGPoint {
public float x;
public float y;
};
[StructLayout(LayoutKind.Sequential)]
public struct CGSize {
public float width;
public float height;
};
[StructLayout(LayoutKind.Sequential)]
public struct CGRect {
public CGPoint origin;
public CGSize size;
}
public class UnityBridge : MonoBehaviour {
#region Declare external C interface
// #if UNITY_IOS && !UNITY_EDITOR
[DllImport("__Internal")]
private static extern int _vision_detectObjectsIn(IntPtr texture);
delegate bool ObjectDetectedCallback(ref CGRect rect);
[DllImport("__Internal")]
private static extern void _vision_setDelegate(ObjectDetectedCallback callback);
[MonoPInvokeCallback(typeof(ObjectDetectedCallback))]
private static bool delegateMessageReceived(ref CGRect rect) {
Debug.Log("Message received: " + rect.origin.x);
return true;
}
// #endif
#endregion
public void initializeDelegate() {
if (Application.platform == RuntimePlatform.IPhonePlayer) {
_vision_setDelegate(delegateMessageReceived);
}
}
#region Wrapped methods and properties
public void EvaluateTexture(IntPtr texture) {
initializeDelegate();
if (texture == IntPtr.Zero) {
Debug.LogError("[Texture] Pointer to buffer is null.");
return;
}
bool success;
#if UNITY_IOS && !UNITY_EDITOR
_vision_detectObjectsIn(texture);
#endif
}
#endregion
#region Singleton implementation
private static WeRDetectorUnity _instance;
public static WeRDetectorUnity Instance {
get {
if (_instance == null) {
var obj = new GameObject("WeRDetectorUnity");
_instance = obj.AddComponent<WeRDetectorUnity>();
}
return _instance;
}
}
void Awake() {
if (_instance != null) {
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
}
#endregion
}
Unity中的消息接收打印不会返回应有的1,而是一个奇怪的指数小数。 有什么想法吗?
答案 0 :(得分:0)
您需要为传递参数创建结构,它可以多次使用参数,也可以在主类中访问。
struct Location {
let latitude:"latitude"
let longitude: "longitude"
}