我肯定错过了什么。我一直在阅读有关 FFI 的文章,但似乎无法得到明确的答案。假设我有以下 C++ 函数:
extern "C" {
int ReturnAnArrayOfStrings(const char* arrayOfStrings[]) {
if( NULL == arrayOfStrings ) return someCharList.size();
for(auto iter = someCharList.begin(), auto index = 0; iter != someCharList.end(); ++iter, ++index) {
char* allocatedHere = new char[strlen(*iter)]; // note that this is not freed
strcpy_s(allocatedHere, strlen(*iter), *iter);
arrayOfStrings[index] = allocatedHere;
}
return someCharList.size();
}
}
据我所知,如果从 FFI 使用它,您所要做的就是以下内容:
module SomeDll
extend FFI::Library
ffi_lib 'SomeDll.dll'
attach_function :get_strings, :ReturnAnArrayOfStrings, [:pointer], :int
end
include SomeDll
pointer = FFI::MemoryPointer.new :pointer, get_strings(nil) # how many strings are there?
get_strings pointer
pointer.get_array_of_string(0).each do |value|
puts value
end
我的问题是:谁来清理内存? C++ 方法是
new
'ing up char* 但从不释放它。 FFI 会处理吗?我在这里缺少什么?提前致谢。
最佳答案
Ruby FFI 试图在谁拥有内存方面保持对称——如果你分配它(即 C 代码),你必须释放它。相反,如果 FFI 分配它,它单独可以释放它。
你没有发布你的 FreeStrings() 函数,但假设它看起来有点像:
void FreeStringArray(char **strings, int len) {
for (int i = 0; i < len; ++i) {
delete[] strings[i];
}
// Do _NOT_ free 'strings' itself, that is managed by FFI
}
你这样使用它:
module SomeDll
extend FFI::Library
ffi_lib 'SomeDll.dll'
attach_function :get_strings, :ReturnAnArrayOfStrings, [:pointer], :int
attach_function :free_strings, :FreeStringArray, [ :pointer, :int ], :void
end
include SomeDll
count = get_strings(nil)
strings = FFI::MemoryPointer.new :pointer, count
get_strings strings
strings.get_array_of_string(0, count).each do |value|
puts value
end
# free each element of the array
free_strings(strings, count)
那么这应该有效。
等效的 C 代码将是:
int count = ReturnArrayOfStrings(NULL);
// Allocate an array for the pointers. i.e. FFI::MemoryPointer.new :pointer, count
char **ptr_array = (char **) calloc(count, sizeof(char *));
ReturnArrayOfStrings(ptr_array);
for (int i = 0; i < count; ++i) {
printf("string[%d]=%s\n", i, ptr_array[i]);
}
// Free each element of the array (but not the array itself)
FreeStringArray(ptr_array, count);
// free the array itself. i.e FFI::MemoryPointer garbage-collecting its memory
free(ptr_array);
关于c++ - FFI/MemoryPointer 内存分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14066708/