2015-09-09 80 views
1

我有編譯問題與libmodbus。我有以下代碼升壓shared_ptr的使用typedef結構

boost::shared_ptr <modbus_t> ctx; 
ctx->modbus_new_tcp(ip_address.c_str(), modbus_port); 

,但我得到以下錯誤

error: invalid use of incomplete type 'struct _modbus' 

它指向此行modbus.h

typedef struct _modbus modbus_t; 

我沒有足夠的瞭解這個解決我的問題。你覺得它是什麼?這個庫不能與智能指針兼容嗎?他們告訴你使用正規指針

modbus_t* ctx; 

謝謝。

回答

1

事實上,這似乎是一個C風格的API,他們已經完全隱藏了您作爲用戶的modbus_t的實現(因爲您將指針傳遞給自由函數而不是調用對象成員)。

這是什麼意思,你不能使用shared_ptr開箱(因爲它需要定義調用delete,這也恰好是錯誤的調用)。有可能是一種使用調用相應的清理功能(可能是modbus_free)的自定義刪除程序的方式。您隨後必須使用.get()才能在您想要調用API時獲取原始指針。

+0

謝謝。我在他們的頁面上提出了一個問題 – xinthose

+0

您肯定*可以*使用自定義刪除程序來調用您想要的任何功能。 – Puppy

3

你可能 - 也許 - 使用

if (std::unique_ptr<modbus_t, void(*)(modbus_t*)> mb(modbus_new_tcp(ip_address.c_str(), modbus_port), &modbus_free)) { 

    modbus_connect(mb); 

    /* Read 5 registers from the address 0 */ 
    modbus_read_registers(mb, 0, 5, tab_reg); 

    modbus_close(mb); 
} // modbus_free invoked, even in the case of exception. 

這當然,假設有獨特的所有權。

+4

謝謝。我希望c程序員會擁抱Boost更多 – xinthose

+0

@xinthose謝謝。我同意,但我想指出,在這個答案中沒有任何提升特定的:) – sehe