我正在从 NetCore 应用程序调用用 C 编写的第三方库。问题是,为了使用这个库,我首先需要进行调用并配置一个复杂的结构,该结构稍后必须传递给所有后续调用。
void createCtx(modbus_t ** ctx)
{
*ctx = modbus_new_tcp("192.168.1.175", 502);
//configure the context here ....
int res = modbus_connect(*ctx);
}
int pollData(modbus_t * ctx)
{
//....
modbus_read_bits(ctx, addr, 1, tab_rp_bits);
//....
}
我的方法是在调用者应用程序 (C#) 上创建 modbus_t 对象,通过调用 createCtx 对其进行配置,然后定期将其传递给 pollData。我已经阅读了有关 StructLayout 的内容,但由于我不需要访问 modbusContext 对象中的数据,我只想为上下文保留一块内存,让 C# 忘记里面的内容。
这就是我想出的
static IntPtr modbusContext;
static class ModbusDriver
{
[DllImport("modbusdriver",EntryPoint = "createCtx")]
public static extern void CreateCtx(ref IntPtr modbusContext);
[DllImport("modbusdriver",EntryPoint = "pollData")]
public static extern uint PollData(IntPtr modbusContext)
}
static void Main(string[] args)
{
int ctxSize = ModbusDriver.GetCtxSize();
modbusContext = Marshal.AllocHGlobal(80 * Marshal.SizeOf(typeof(byte))); //<--- 80 is the result of sizeof(modbus_t)
ModbusDriver.CreateCtx(ref modbusContext);
while(true)
{
ModbusDriver.PollData(modbusContext);
Thread.Sleep(1000);
}
}
}
这一切似乎都行得通,但感觉不太对劲,尤其是因为 modbus_t 结构相当复杂
struct modbus_t {
/* Slave address */
int slave;
/* Socket or file descriptor */
int s;
int debug;
int error_recovery;
struct timeval response_timeout;
struct timeval byte_timeout;
struct timeval indication_timeout;
const modbus_backend_t *backend;
void *backend_data;
};
所以我的问题是,我的方法正确吗?具体来说, modbus_t 包含指针。我设法在 C# 中保留了 modbus_t 结构,它似乎可以工作,但是假设结构中包含的指针引用的内存在调用之间不会被破坏真的安全吗?感觉不对。
元芳怎么了
相关分类