DLL函数C ++而不是C [英] DLL functions C++ instead of C

查看:79
本文介绍了DLL函数C ++而不是C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我在边界DLL调用上使用了简单类型。但问题是,当DLL使用智能指针时:



示例:

  auto client = std :: make_unique< Client>(* conf);

  auto table = client-> Table(* tn);

表是智能指针



表* soGetTable(Cleitn * client,char *姓名)

{

//

   return client-> Table(* tn).get();  //< ======这里

}

它释放指针

解决方案

< blockquote>

std :: unique_ptr的release成员使unique_ptr不再拥有指针。


当然,问题实际上是清理指针,因为它不是由unique_ptr更长时间拥有,如果你将它传递出动态库,那么由于应用程序和动态库
使用不同版本的CRT,它可能无法解除分配。


如果您可以保证呼叫在同一模块中转移所有权,或者模块将始终使用相同版本的DLL CRT,那么您只需执行以下操作:

表* soGetTable(Cleitn * client,char * name)
{
//
   return client-> Table(* tn)。release();  //< ======这里
}

在电话的另一边,做:


< pre class ="prettyprint"> std :: unique_ptr< Table> PTR;
ptr.reset(soGetTable(param,param));

这将转移两个unique_ptrs之间的所有权。


但是如果你要在两个具有不同CRT的模块之间进行操作,那么你需要做更多的工作,因为DLL需要释放Table对象的内存。


So far I used simple types on boundary DLL calling. But is problem, when DLL uses smart pointers:

Example:
  auto client = std::make_unique<Client>(*conf);
  auto table = client->Table(*tn);
table is smart pointer

Table *soGetTable(Cleitn *client, char *name)
{
//
   return client->Table(*tn).get();  //<====== here
}
it frees pointer

解决方案

The release member of std::unique_ptr makes the unique_ptr no longer own the pointer.

Of course, the problem then is actually cleaning up the pointer, because it is no longer owned by a unique_ptr, and if you are passing it out of the dynamic library, then it is possible that it may fail to deallocate due to the application and dynamic library using different versions of the CRT.

If you can guarantee that the call is transferring ownership in the same module, or the modules will always use the same version of the DLL CRT, then you can simply do:

Table *soGetTable(Cleitn *client, char *name)
{
//
   return client->Table(*tn).release();  //<====== here
}

And on the other side of the call, do:

std::unique_ptr<Table> ptr;
ptr.reset(soGetTable(param, param));

This will transfer ownership between the two unique_ptrs.

If however you are going between two modules which have different CRTs, then you need to do more work, since the DLL will need to be what frees the memory of the Table object.


这篇关于DLL函数C ++而不是C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆