c++ - C++-使用uint8_t指针将字符串值传递给函数

标签 c++ pointers hadoop impala

我正在学习C++,以便创建要在Hadoop Cloudera Impala SQL中使用的自定义函数(用户定义的函数就是cloudera称呼它)。 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_t类型的指针?我尝试了以下操作,但是收到了“错误:无法在分配中将std::string转换为uint8_t *” *
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);

最佳答案

字符串本身不是字符指针(这是您需要的),但是您可以使用c_str函数获得一个。

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

如果要使用新样式的转换,则可能需要const_cast(将const char *转换为char *)和reinterpret_cast,这取决于str.ptr的定义方式。

关于c++ - C++-使用uint8_t指针将字符串值传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35362688/

相关文章:

c++ - C++中整数和指针之间的转换

c++ - 递归函数c++的段错误

mongodb - 映射器无法让Pig将数据插入MongoDB

hadoop - 压缩 HDFS 文件时出现 IOException

c++是否对置换算法使用类

c++ - QSerialPort 正确发送多行

c - fread 在c中用随机字符填充字符串

hadoop - Oozie EL 函数中的动态变量

c++ - 设置全局指针

c++ - Swig C++ : Interfacing vector<Class object *>