【问题标题】:MySQL User Defined Functions in C++C++ 中的 MySQL 用户定义函数
【发布时间】:2017-09-06 14:34:45
【问题描述】:

我正在尝试运行用 C++ 编写的 MySQL UDF。它编译良好并生成正确的输出,但在输出后会生成很多垃圾。我想知道这个垃圾的原因以及如何解决这个问题?我附上了我的代码和输出的屏幕截图。

#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include "mysql-connector-c-6.1.9-linux-glibc2.5-x86_64/include/mysql.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/mysql_connection.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/sqlstring.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/resultset.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/datatype.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/resultset.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/resultset_metadata.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/exception.h"

using namespace std;

extern "C" {
    char *hello_world (UDF_INIT *initid, UDF_ARGS *args,char *result, unsigned long length,char *is_null, char *error);
    my_bool hello_world_init (UDF_INIT *initid, UDF_ARGS *args, char *message);
    void hello_world_deinit (UDF_INIT *initid);
    //template <typename T>  T adder (UDF_INIT *initid, UDF_eARGS *args,string result, unsigned long length,string is_null, string error,T v);
}

char *hello_world (UDF_INIT *initid, UDF_ARGS *args, char *result, unsigned long length, char *is_null, char *error)
{
    string res;
    res = args->args[0];
    res.append(" hello");
    char *c = new char[res.size()];
    strcpy(c, res.c_str());
    return c;
}

my_bool hello_world_init (UDF_INIT *initid, UDF_ARGS *args, char *message)
{
    return 0;
    //cout<<"success"<<endl;
}

void hello_world_deinit (UDF_INIT *initid)
{
    return;
}

enter image description here

【问题讨论】:

  • 作为结果分配的数组太小。您需要为终止零添加一个字符:new char[res.size() + 1]
  • 你为结果分配的缓冲区会导致内存泄漏。您需要在xxx_initxxx_deinit 函数中管理内存:预先分配一个缓冲区来存储结果并在之后释放它。

标签: c++ mysql-udf


【解决方案1】:

hello_world 函数的签名错误。第四个参数应该是

unsigned long *length

该指针指向的值必须设置为返回字符串的长度。

char *c = new char[res.size() + 1];
strcpy(c, res.c_str());
*length = res.size();
return c;

【讨论】:

    猜你喜欢
    • 2010-12-27
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2020-10-12
    • 1970-01-01
    相关资源
    最近更新 更多