DLL中的新内存,在另一个项目中使用它 [英] New memory in DLL that using it in another projects

查看:79
本文介绍了DLL中的新内存,在另一个项目中使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





在Dll项目(VC ++)中,我定义了一个获取wchar_t *并在参数中返回wchar_t *的函数。

我的问题是:创建指定大小的指针(new wchar_t *)然后将其作为参数引用返回是否正确?

在我的代码中像sret:

Hi,

In a Dll project (VC++) , I defined a function that get wchar_t* and return wchar_t* in a parameter.
My Question is this: Is it correct to create the pointer(new wchar_t*) with specified size then return it as parameter refernce ?
like "sret" in my code:

extern "C"
{

	__declspec(dllexport) int  Function(wchar_t*  s, wchar_t*  sret,  int len)
	{
		int sLen = wcslen(s);
		sret = new wchar_t(sLen+4);
		wcscpy_s(sret, sLen, s);
		wcscat_s(sret, 4, L"_456");
		len = wcslen(sret);
		return 1;
	}
}





我想在其他Windows项目中使用这个dll。他们的记忆不会出现问题?



我尝试过:



新的wchar_t *进入一个dll函数然后返回它



I want to use this dll in other windows projects . They's memory doesn't occur with problems?

What I have tried:

new the wchar_t* into a dll function then return it

推荐答案

这不起作用,因为 sret 是一个本地指针,因此调用应用程序仍然会将其指向其他位置。你需要指针的地址,例如:

This will not work because sret is a local pointer, so the calling application will still have it pointing somewhere else. You need the address of the pointer, something like:
__declspec(dllexport) int  Function(wchar_t*  s, wchar_t**  sret,  int len)
{
    int sLen = wcslen(s);
    *sret = new wchar_t(sLen+4); // should be sLen + 5
    wcscpy_s(*sret, sLen, s);
    wcscat_s(*sret, 4, L"_456");
    len = wcslen(*sret); // what is this line for?

    return 1; // what is this line for?
}



然而,更好的方法是返回指针,例如:


However, a much better way would be to just return the pointer, something like:

__declspec(dllexport) wchar_t* Function(wchar_t*  s)
{
    int sLen = wcslen(s);
    wchar_t* sret = new wchar_t[sLen + 5];
    wcscpy_s(sret, sLen, s);
    wcscat_s(sret, 4, L"_456");

    return sret;
}



您是否认为这需要在DLL中?


Is there a specific reason that you think this needs to be in a DLL?


除了 Richard 解决方案,请看 c ++ - 在DLL中分配内存并将指针指向客户端应用程序是不好的做法? - 堆栈溢出 [ ^ ]。

遗憾的是,分配器和解除分配器之间的不匹配确实发生了不愉快。
In addition to Richard solution, have a look at c++ - Is it bad practice to allocate memory in a DLL and give a pointer to it to a client app? - Stack Overflow[^].
Unfortunately mismatches between allocator and deallocator do happen and are not pleasant.


这篇关于DLL中的新内存,在另一个项目中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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