c++使用uint8\u t指针将字符串值传递给函数

sz81bmfz  于 2021-05-29  发布在  Hadoop
关注(0)|答案(2)|浏览(855)

我学习c++是为了创建一个自定义函数(用户定义的函数是cloudera如何调用的),我想在hadoop cloudera impala sqls中使用它。cloudera提供了一个头文件,其中包含自定义函数参数的类型定义

struct AnyVal {
  bool is_null;
  AnyVal(bool is_null = false) : is_null(is_null) {}
};
//Integer Value
struct IntVal : public AnyVal {
  int32_t val;

  IntVal(int32_t val = 0) : val(val) { }

  static IntVal null() {
    IntVal result;
    result.is_null = true;
    return result;
  }
}
//String Value
struct StringVal : public AnyVal {
  static const int MAX_LENGTH = (1 << 30);
  int len;
  uint8_t* ptr;
  /// Construct a StringVal from ptr/len. Note: this does not make a copy of ptr
  /// so the buffer must exist as long as this StringVal does.
  StringVal(uint8_t* ptr = NULL, int len = 0) : len(len), ptr(ptr) {
    assert(len >= 0);
  };
  /// Construct a StringVal from NULL-terminated c-string. Note: this does not make a copy of ptr so the underlying string must exist as long as this StringVal does.
  StringVal(const char* ptr) : len(strlen(ptr)), ptr((uint8_t*)ptr) {}

  static StringVal null() {
    StringVal sv;
    sv.is_null = true;
    return sv;
  }
}

现在,对于下面这样一个简单的add函数,我理解了在设置intval.val之后如何传递intval对象的引用,并且成功了!

IntVal AddUdf(FunctionContext* context, const IntVal& arg1, const IntVal& arg2) {
  if (arg1.is_null || arg2.is_null) return IntVal::null();
  return IntVal(arg1.val + arg2.val);
} 

int main() {
impala_udf::FunctionContext *FunctionContext_t ;
IntVal num1, num2 , res;
num1.val=10;
num2.val=20;
IntVal& num1_ref = num1;
IntVal& num2_ref = num2;
res = AddUdf(FunctionContext_t, num1_ref, num2_ref);
cout << "Addition Result = " << res.val << "\n";
}

但我不知道如何对字符串函数执行类似的操作,因为stringval要求我为字符串传递uint8\u t类型的指针?我尝试了下面的一个,但收到“错误:无法将std::string转换为uint8\u tin assignment”

int main() {
impala_udf::FunctionContext *FunctionContext_t ;
StringVal str , res;
string input="Hello";
str.len=input.length();
str.ptr=&input;
StringVal& arg1=str;
res = StripVowels(FunctionContext_t, str);
cout << "Result = " << (char *) res.ptr<< "\n";
}

我也试过以下方法,但没有什么乐趣。任何指向正确方向的指针都将不胜感激。谢谢。

str.ptr=reinterpret_cast<uint8_t*>(&input);
zpjtge22

zpjtge221#

字符串本身不是字符指针(这是您所需要的),但是您可以通过使用c\u str函数获得一个。

str.ptr=(uint8_t*)(input.c_str ());

如果要使用新样式的转换,可能需要const\u转换(从const char转换为char)和reinterpret\u转换,具体取决于str.ptr的定义方式。

oymdgrw7

oymdgrw72#

这是因为您需要一个指向c-string的指针,并且您提供了一个指向 std::string . str.ptr = input.c_str() 应该对你有用。
编辑:但是,似乎您需要一个非常量指针。在这种情况下,您需要分配 input 你自己,比如: char input[128]; 这将在堆栈上创建一个固定大小的数组。但您可能希望使用新的动态分配: char* input = new char[size]; 另外,请检查cstring头中的函数,您可能希望使用这些函数。
你可能还需要把它投给 uint8_t* 如上所述。
别忘了 delete[] 当你不再需要它的时候再把它拿出来。但是既然你把它传递给一个函数,这个函数就应该处理这个问题。

相关问题