我需要将C代码接口到LabVIEW,我的C函数需要返回一个二维字符串数组。我不想被迫预先确定阵列的大小。所以我想知道,正确的数据格式是什么(处理C字符串指针数组?字符串句柄数组的句柄?),如何正确进行分配,以及使用数组参数还是返回类型更好。为Call Library函数节点提供的对话框只支持数值类型的数组,所以我对如何构造它有些迷茫。
最佳答案
你需要LabVIEW Code Interface Reference Manual来解决这个问题。
您正在编写一个C函数,该函数将向LabVIEW返回一个2D字符串数组。这意味着您需要返回LabVIEW的数据结构并使用LabVIEW的内存分配器。在C文件中包含“extcode.h”(LabVIEW附带)。然后创建以下C代码:
#include "extcode.h"
struct String2DArrayBlock {
int32 dimensionSize1;
int32 dimensionSize2;
LStrHandle stringArray[1]; // Yes, this is intentional. Do not use LStrHandle* because that syntax changes the memory allocation. Old-school C code. LabVIEW's own C++ code has wrappers for managing this with more type safety.
};
typedef String2DArrayBlock** String2DArrayHandle;
MgErr GenerateMyStrings(String2DArrayHandle *ptrToHandle) {
if (!ptrToHandle)
return mgArgErr; // Gotta pass a location for us to allocate.
if (*ptrToHandle) {
// This handle is already allocated. I'm not going to walk you through all the code needed to deallocate.
return mgArgErr;
}
const int32 dimSize1 = ComputeHeight(); // This is your function... whereever your data is coming from.
const int32 dimSize2 = ComputeWidth(); // Same here.
const int32 numberOfElements = dimSize1 * dimSize2;
if (numberOfElements == 0) {
return mgNoErr; // Done. NULL means empty array, and the handle is already NULL.
}
// DSNewHClr allocates the block and flood fills it with all zeros.
*ptrToHandle = (String2DArrayHandle)DSNewHClr(sizeof(String2DArrayBlock) + ((numberOfElements - 1) * sizeof(LStrHandle))); // -1 because the sizeof block has 1 element.
if (!*ptrToHandle)
return mFullErr; // Out of memory
(**ptrToHandle)->dimensionSize1 = dimSize1;
(**ptrToHandle)->dimensionSize2 = dimSize2;
LStrHandle *current = (**ptrToHandle)->stringArray;
for (int32 i = 0; i < numberOfElements; ++i, ++current) {
std::string myCurrentString = GetMyCurrentString(i); // You write this however you look up the individual strings.
if (myCurrentString.empty())
continue; // NULL means empty string
*current = (LStrHandle)DSNewHClr(sizeof(LStr)); // Allocates a zero-length LStrHandle.
if (!*current)
return mFullErr; // The array will be partially filled, but it is in a safe state for early return.
MgErr err = LStrPrintf(*current, (CStr)"%s", myCurrentString.c_str());
if (err)
return err; // The array will be partially filled, but it is in a safe state for early return.
}
return mgNoErr;
}
根据LabVIEW运行时引擎(lvrt.dll)编译代码。
在G代码中,删除一个调用库节点,添加一个“Adapt to type”和“Pointers to Handles”参数,并将其与一个空的2D数组关联。你完了。
关于c - LabVIEW调用库函数产生字符串数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58628446/