【发布时间】:2017-10-12 10:24:29
【问题描述】:
这是我的代码:
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using System;
using System.IO;
public class CarMove : MonoBehaviour
{
public unsafe struct TrafficRoadSystem { };
public unsafe struct CarsSimulation { };
public unsafe struct CarPostion
{
double position_x;
double position_y;
double position_z;
};
// Use this for initialization
[DllImport("Assets/traffic.dll", CharSet = CharSet.Ansi)]
public unsafe static extern int traffic_import_osm([MarshalAs(UnmanagedType.LPStr)] string osm_pbf_path, TrafficRoadSystem** out_road_system);
[DllImport("Assets/traffic.dll")]
public unsafe static extern int create_simulation(TrafficRoadSystem* road_system, CarsSimulation** out_simulation, double speed, int cars_count);
[DllImport("Assets/traffic.dll")]
public static extern void update_simulation(ref CarsSimulation simulation, double time);
[DllImport("Assets/traffic.dll")]
public static extern CarPostion get_car_postion(ref CarsSimulation simulation, int car_number);
unsafe CarsSimulation* carSimulation;
unsafe TrafficRoadSystem* trafficRoadSystem;
void Start()
{
unsafe
{
string osmPath = "Assets/Resources/map.osm.pbf";
int results;
results = traffic_import_osm(osmPath, &trafficRoadSystem);
}
}
// Update is called once per frame
void Update()
{
}
}
这是来自 dll C 库。函数int traffic_import_osm() 作用于TrafficRoadSystem* trafficRoadSystem; 对象作为参考,我想访问void Update() 中的对象。这在一个函数中运行良好,但我无法获取类变量的地址并且出现错误
Error CS0212 You can only take the address of an unfixed expression inside of a fixed statement initializer
在线results = traffic_import_osm(osmPath, &trafficRoadSystem);
我尝试使用此解决方案 https://msdn.microsoft.com/en-us/library/29ak9b70(v=vs.90).aspx
这是我写的:
TrafficRoadSystem trafficRoadSystem;
void Start()
{
unsafe
{
string osmPath = "Assets/Resources/map.osm.pbf";
CarMove carMove = new CarMove();
int results;
fixed( TrafficRoadSystem* ptr = &carMove.trafficRoadSystem)
{
results = traffic_import_osm(osmPath, &ptr);
}
}
}
我在行中收到错误CS0459 Cannot take the address of a read-only local variable
results = traffic_import_osm(osmPath, &ptr);
【问题讨论】:
-
您不能只是复制/粘贴 C 声明并希望它会起作用。该函数很难从 C 程序中调用,当您必须调用它时,它永远不会变得更好。它看起来 像是在尝试返回对数组的引用。但是要使用它,您必须知道数组中的元素数量,也许 int 返回值会告诉您这一点。您无法判断是否应该释放数组的内存。您唯一的希望是元素上的 IntPtr 和 Marshal.PtrToStructure 。但你最好先索要编程手册。