How to load deep learning model in jni - deep-learning
https://github.com/huaweicodelabs/HiAI-Foundation
I have a question about the above site.
Preparation && Getting Started,
5.Before using a model, you need to load the model.
The DDK supports both single-model and multi-model loading.
In sync mode, the app layer loads the model by calling the loadModelSync function at the JNI layer.
In async mode, the app layer loads the model by calling the loadModelAsync function at the JNI layer.
Here, it says to load the model in JNI, but I'm not sure.
If it was keras in python
model = load_model ('squeezenet_v1.0.caffemodel')
I think I will write.
Assuming that you use squeezenet_v1.0.caffemodel, please tell me how to write it.
classify_sync_jni.cpp
/**
* #file classify_jni.cpp
*
* Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <jni.h>
#include <string>
#include <memory.h>
#include "HiAiModelManagerService.h"
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/log.h>
#include <cstdlib>
#include <cmath>
#include <sstream>
#include <sys/time.h>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#define LOG_TAG "SYNC_DDK_MSG"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
// 如果expr为true,则执行exec_expr,不打印日志
#define IF_BOOL_EXEC(expr, exec_expr) \
{ \
if (expr) { \
exec_expr; \
} \
}
using namespace std;
using namespace hiai;
static shared_ptr<AiModelMngerClient> g_clientSync = nullptr;
static vector<vector<TensorDimension>> inputDimension;
static vector<vector<TensorDimension>> outputDimension;
static vector<vector<shared_ptr<AiTensor>>> input_tensor;
static vector<vector<shared_ptr<AiTensor>>> output_tensor;
static map<string, int> g_syncNameToIndex;
static long time_use_sync = 0;
static const int SUCCESS = 0;
static const int FAILED = -1;
void ResourceDestroy(shared_ptr<AiModelBuilder>& modelBuilder, vector<MemBuffer*>& memBuffers)
{
if (modelBuilder == nullptr) {
LOGE("[HIAI_DEMO_SYNC] modelBuilder is null.");
return;
}
for (auto tmpBuffer : memBuffers) {
modelBuilder->MemBufferDestroy(tmpBuffer);
}
return;
}
int LoadSync(vector<string>& names, vector<string>& modelPaths, shared_ptr<AiModelMngerClient>& client)
{
int ret;
vector<shared_ptr<AiModelDescription>> modelDescs;
vector<MemBuffer*> memBuffers;
shared_ptr<AiModelBuilder> modelBuilder = make_shared<AiModelBuilder>(client);
if (modelBuilder == nullptr) {
LOGI("[HIAI_DEMO_SYNC] creat modelBuilder failed.");
return FAILED;
}
for (size_t i = 0; i < modelPaths.size(); ++i) {
string modelPath = modelPaths[i];
string modelName = names[i];
g_syncNameToIndex[modelName] = i;
// We can achieve the optimization by loading model from OM file.
LOGI("[HIAI_DEMO_SYNC] modelpath is %s\n.", modelPath.c_str());
MemBuffer* buffer = modelBuilder->InputMemBufferCreate(modelPath);
if (buffer == nullptr) {
LOGE("[HIAI_DEMO_SYNC] cannot find the model file.");
return FAILED;
}
memBuffers.push_back(buffer);
string modelNameFull = string(modelName) + string(".om");
shared_ptr<AiModelDescription> desc =
make_shared<AiModelDescription>(modelNameFull, AiModelDescription_Frequency_HIGH, HIAI_FRAMEWORK_NONE,
HIAI_MODELTYPE_ONLINE, AiModelDescription_DeviceType_NPU);
if (desc == nullptr) {
LOGE("[HIAI_DEMO_SYNC] LoadModelSync: desc make_shared error.");
ResourceDestroy(modelBuilder, memBuffers);
return FAILED;
}
desc->SetModelBuffer(buffer->GetMemBufferData(), buffer->GetMemBufferSize());
LOGE("[HIAI_DEMO_SYNC] loadModel %s IO Tensor.", desc->GetName().c_str());
modelDescs.push_back(desc);
}
ret = client->Load(modelDescs);
ResourceDestroy(modelBuilder, memBuffers);
if (ret != 0) {
LOGE("[HIAI_DEMO_SYNC] Model Load Failed.");
return FAILED;
}
return SUCCESS;
}
int UpdateSyncInputTensorVec(vector<TensorDimension>& inputDims, bool isUseAipp, string& modelName)
{
input_tensor.clear();
vector<shared_ptr<AiTensor>> inputTensors;
int ret = FAILED;
for (auto inDim : inputDims) {
shared_ptr<AiTensor> input = make_shared<AiTensor>();
if (isUseAipp) {
ret = input->Init(inDim.GetNumber(), inDim.GetHeight(), inDim.GetWidth(), AiTensorImage_YUV420SP_U8);
LOGI("[HIAI_DEMO_SYNC] model %s uses AIPP(input).", modelName.c_str());
} else {
ret = input->Init(&inDim);
LOGI("[HIAI_DEMO_SYNC] model %s does not use AIPP(input).", modelName.c_str());
}
IF_BOOL_EXEC(ret != SUCCESS, LOGE("[HIAI_DEMO_SYNC] model %s AiTensor Init failed(input).", modelName.c_str());
return FAILED);
inputTensors.push_back(input);
}
input_tensor.push_back(inputTensors);
IF_BOOL_EXEC(input_tensor.size() == 0, LOGE("[HIAI_DEMO_SYNC] input_tensor.size() == 0"); return FAILED);
return SUCCESS;
}
int UpdateSyncOutputTensorVec(vector<TensorDimension>& outputDims, string& modelName)
{
output_tensor.clear();
vector<shared_ptr<AiTensor>> outputTensors;
int ret = FAILED;
for (auto outDim : outputDims) {
shared_ptr<AiTensor> output = make_shared<AiTensor>();
ret = output->Init(&outDim);
IF_BOOL_EXEC(ret != SUCCESS, LOGE("[HIAI_DEMO_SYNC] model %s AiTensor Init failed(output).", modelName.c_str());
return FAILED);
outputTensors.push_back(output);
}
output_tensor.push_back(outputTensors);
IF_BOOL_EXEC(output_tensor.size() == 0, LOGE("[HIAI_DEMO_SYNC] output_tensor.size() == 0"); return FAILED);
return SUCCESS;
}
shared_ptr<AiModelMngerClient> LoadModelSync(vector<string> names, vector<string> modelPaths, vector<bool> Aipps)
{
shared_ptr<AiModelMngerClient> clientSync = make_shared<AiModelMngerClient>();
IF_BOOL_EXEC(clientSync == nullptr, LOGE("[HIAI_DEMO_SYNC] Model Manager Client make_shared error.");
return nullptr);
int ret = clientSync->Init(nullptr);
IF_BOOL_EXEC(ret != SUCCESS, LOGE("[HIAI_DEMO_SYNC] Model Manager Init Failed."); return nullptr);
ret = LoadSync(names, modelPaths, clientSync);
IF_BOOL_EXEC(ret != SUCCESS, LOGE("[HIAI_DEMO_ASYNC] LoadSync Failed."); return nullptr);
inputDimension.clear();
outputDimension.clear();
for (size_t i = 0; i < names.size(); ++i) {
string modelName = names[i];
bool isUseAipp = Aipps[i];
LOGI("[HIAI_DEMO_SYNC] Get model %s IO Tensor. Use AIPP %d", modelName.c_str(), isUseAipp);
vector<TensorDimension> inputDims, outputDims;
ret = clientSync->GetModelIOTensorDim(string(modelName) + string(".om"), inputDims, outputDims);
IF_BOOL_EXEC(ret != SUCCESS, LOGE("[HIAI_DEMO_SYNC] Get Model IO Tensor Dimension failed,ret is %d.", ret);
return nullptr);
IF_BOOL_EXEC(inputDims.size() == 0, LOGE("[HIAI_DEMO_SYNC] inputDims.size() == 0"); return nullptr);
inputDimension.push_back(inputDims);
outputDimension.push_back(outputDims);
IF_BOOL_EXEC(UpdateSyncInputTensorVec(inputDims, isUseAipp, modelName) != SUCCESS, return nullptr);
IF_BOOL_EXEC(UpdateSyncOutputTensorVec(outputDims, modelName) != SUCCESS, return nullptr);
}
return clientSync;
}
extern "C" JNIEXPORT jlong JNICALL Java_com_huawei_hiaidemo_utils_ModelManager_GetTimeUseSync(JNIEnv* env, jclass type)
{
return time_use_sync;
}
int setField(JNIEnv* env, int len, jobject& modelInfo, jmethodID listGet)
{
for (int i = 0; i < len; i++) {
jobject modelInfoObj = env->CallObjectMethod(modelInfo, listGet, i);
jclass modelInfoClass = env->GetObjectClass(modelInfoObj);
jfieldID inputIdN = env->GetFieldID(modelInfoClass, "input_N", "I");
jfieldID inputIdC = env->GetFieldID(modelInfoClass, "input_C", "I");
jfieldID inputIdH = env->GetFieldID(modelInfoClass, "input_H", "I");
jfieldID inputIdW = env->GetFieldID(modelInfoClass, "input_W", "I");
jfieldID inputNumber = env->GetFieldID(modelInfoClass, "input_Number", "I");
env->SetIntField(modelInfoObj, inputIdN, inputDimension[i][0].GetNumber());
env->SetIntField(modelInfoObj, inputIdC, inputDimension[i][0].GetChannel());
env->SetIntField(modelInfoObj, inputIdH, inputDimension[i][0].GetHeight());
env->SetIntField(modelInfoObj, inputIdW, inputDimension[i][0].GetWidth());
env->SetIntField(modelInfoObj, inputNumber, inputDimension[i].size());
jfieldID outputIdN = env->GetFieldID(modelInfoClass, "output_N", "I");
jfieldID outputIdC = env->GetFieldID(modelInfoClass, "output_C", "I");
jfieldID outputIdH = env->GetFieldID(modelInfoClass, "output_H", "I");
jfieldID outputIdW = env->GetFieldID(modelInfoClass, "output_W", "I");
jfieldID outputNumber = env->GetFieldID(modelInfoClass, "output_Number", "I");
env->SetIntField(modelInfoObj, outputIdN, outputDimension[i][0].GetNumber());
env->SetIntField(modelInfoObj, outputIdC, outputDimension[i][0].GetChannel());
env->SetIntField(modelInfoObj, outputIdH, outputDimension[i][0].GetHeight());
env->SetIntField(modelInfoObj, outputIdW, outputDimension[i][0].GetWidth());
env->SetIntField(modelInfoObj, outputNumber, outputDimension[i].size());
}
return SUCCESS;
}
extern "C" JNIEXPORT jobject JNICALL Java_com_huawei_hiaidemo_utils_ModelManager_loadModelSync(
JNIEnv* env, jclass type, jobject modelInfo)
{
jclass classList = env->GetObjectClass(modelInfo);
IF_BOOL_EXEC(classList == nullptr, LOGE("[HIAI_DEMO_SYNC] can not find List class."); return nullptr);
jmethodID listGet = env->GetMethodID(classList, "get", "(I)Ljava/lang/Object;");
jmethodID listSize = env->GetMethodID(classList, "size", "()I");
int len = static_cast<int>(env->CallIntMethod(modelInfo, listSize));
vector<string> names, modelPaths;
vector<bool> aipps;
for (int i = 0; i < len; i++) {
jobject modelInfoObj = env->CallObjectMethod(modelInfo, listGet, i);
jclass modelInfoClass = env->GetObjectClass(modelInfoObj);
jmethodID getOfflineModelName = env->GetMethodID(modelInfoClass, "getOfflineModelName", "()Ljava/lang/String;");
jmethodID getModelPath = env->GetMethodID(modelInfoClass, "getModelPath", "()Ljava/lang/String;");
jmethodID getUseAIPP = env->GetMethodID(modelInfoClass, "getUseAIPP", "()Z");
IF_BOOL_EXEC(getOfflineModelName == nullptr, LOGE("[HIAI_DEMO_SYNC] can not find getOfflineModelName method.");
return nullptr);
IF_BOOL_EXEC(getModelPath == nullptr, LOGE("[HIAI_DEMO_SYNC] can not find getModelPath method.");
return nullptr);
IF_BOOL_EXEC(getUseAIPP == nullptr, LOGE("[HIAI_DEMO_SYNC] can not find getUseAIPP method."); return nullptr);
jboolean useaipp = (jboolean)env->CallBooleanMethod(modelInfoObj, getUseAIPP);
jstring modelname = (jstring)env->CallObjectMethod(modelInfoObj, getOfflineModelName);
jstring modelpath = (jstring)env->CallObjectMethod(modelInfoObj, getModelPath);
const char* modelName = env->GetStringUTFChars(modelname, 0);
LOGI("[HIAI_DEMO_SYNC] modelName is %s .", modelName);
IF_BOOL_EXEC(modelName == nullptr, LOGE("[HIAI_DEMO_SYNC] modelName is invalid."); return nullptr);
const char* modelPath = env->GetStringUTFChars(modelpath, 0);
IF_BOOL_EXEC(modelPath == nullptr, LOGE("[HIAI_DEMO_SYNC] modelPath is invalid."); return nullptr);
LOGE("[HIAI_DEMO_SYNC] useaipp is %d.", bool(useaipp == JNI_TRUE));
aipps.push_back(bool(useaipp == JNI_TRUE));
names.push_back(string(modelName));
modelPaths.push_back(string(modelPath));
}
// load
IF_BOOL_EXEC(!g_clientSync, g_clientSync = LoadModelSync(names, modelPaths, aipps); IF_BOOL_EXEC(
g_clientSync == nullptr, LOGE("[HIAI_DEMO_SYNC] g_clientSync loadModel is nullptr."); return nullptr));
LOGI("[HIAI_DEMO_SYNC] sync load model INPUT NCHW : %d %d %d %d.", inputDimension[0][0].GetNumber(),
inputDimension[0][0].GetChannel(), inputDimension[0][0].GetHeight(), inputDimension[0][0].GetWidth());
LOGI("[HIAI_DEMO_SYNC] sync load model OUTPUT NCHW : %d %d %d %d.", outputDimension[0][0].GetNumber(),
outputDimension[0][0].GetChannel(), outputDimension[0][0].GetHeight(), outputDimension[0][0].GetWidth());
setField(env, len, modelInfo, listGet);
return modelInfo;
}
int runProcess(JNIEnv* env, jobject bufList, jmethodID listGet, int vecIndex, int listLength, const char* modelName)
{
for (int i = 0; i < listLength; i++) {
jbyteArray buf_ = (jbyteArray)(env->CallObjectMethod(bufList, listGet, i));
jbyte* dataBuff = nullptr;
int dataBuffSize = 0;
dataBuff = env->GetByteArrayElements(buf_, nullptr);
dataBuffSize = env->GetArrayLength(buf_);
IF_BOOL_EXEC(input_tensor[vecIndex][i]->GetSize() != dataBuffSize,
LOGE("[HIAI_DEMO_SYNC] input->GetSize(%d) != dataBuffSize(%d) ",
input_tensor[vecIndex][i]->GetSize(), dataBuffSize);
return FAILED);
memmove(input_tensor[vecIndex][i]->GetBuffer(), dataBuff, (size_t)dataBuffSize);
env->ReleaseByteArrayElements(buf_, dataBuff, 0);
}
AiContext context;
string key = "model_name";
string value = modelName;
value += ".om";
context.AddPara(key, value);
LOGI("[HIAI_DEMO_SYNC] runModel modelname:%s", modelName);
// before process
struct timeval tpstart, tpend;
gettimeofday(&tpstart, nullptr);
int istamp;
int ret = g_clientSync->Process(context, input_tensor[vecIndex], output_tensor[vecIndex], 1000, istamp);
IF_BOOL_EXEC(ret, LOGE("[HIAI_DEMO_SYNC] Runmodel Failed!, ret=%d\n", ret); return FAILED);
// after process
gettimeofday(&tpend, nullptr);
float time_use = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;
time_use_sync = time_use / 1000;
LOGI("[HIAI_DEMO_SYNC] inference time %f ms.\n", time_use / 1000);
return SUCCESS;
}
extern "C" JNIEXPORT jobject JNICALL Java_com_huawei_hiaidemo_utils_ModelManager_runModelSync(
JNIEnv* env, jclass type, jobject modelInfo, jobject bufList)
{
// check params
IF_BOOL_EXEC(env == nullptr, LOGE("[HIAI_DEMO_SYNC] runModelSync env is null"); return nullptr);
jclass ModelInfo = env->GetObjectClass(modelInfo);
IF_BOOL_EXEC(ModelInfo == nullptr, LOGE("[HIAI_DEMO_SYNC] can not find ModelInfo class."); return nullptr);
IF_BOOL_EXEC(bufList == nullptr, LOGE("[HIAI_DEMO_SYNC] buf_ is null."); return nullptr);
jmethodID getOfflineModelName = env->GetMethodID(ModelInfo, "getOfflineModelName", "()Ljava/lang/String;");
jmethodID getModelPath = env->GetMethodID(ModelInfo, "getModelPath", "()Ljava/lang/String;");
IF_BOOL_EXEC(getOfflineModelName == nullptr, LOGE("[HIAI_DEMO_SYNC] can not find getOfflineModelName method.");
return nullptr);
IF_BOOL_EXEC(getModelPath == nullptr, LOGE("[HIAI_DEMO_SYNC] can not find getModelPath method."); return nullptr);
jstring modelname = (jstring)env->CallObjectMethod(modelInfo, getOfflineModelName);
jstring modelpath = (jstring)env->CallObjectMethod(modelInfo, getModelPath);
const char* modelName = env->GetStringUTFChars(modelname, 0);
IF_BOOL_EXEC(modelName == nullptr, LOGE("[HIAI_DEMO_SYNC] modelName is invalid."); return nullptr);
int vecIndex = g_syncNameToIndex[modelName];
const char* modelPath = env->GetStringUTFChars(modelpath, 0);
IF_BOOL_EXEC(modelPath == nullptr, LOGE("[HIAI_DEMO_SYNC] modelPath is invalid."); return nullptr);
// buf_list
jclass classList = env->GetObjectClass(bufList);
IF_BOOL_EXEC(classList == nullptr, LOGE("[HIAI_DEMO_SYNC] can not find List class."); return nullptr);
jmethodID listGet = env->GetMethodID(classList, "get", "(I)Ljava/lang/Object;");
jmethodID listSize = env->GetMethodID(classList, "size", "()I");
IF_BOOL_EXEC(listGet == nullptr, LOGE("[HIAI_DEMO_SYNC] can not find get method."); return nullptr);
IF_BOOL_EXEC(listSize == nullptr, LOGE("[HIAI_DEMO_SYNC] can not find size method."); return nullptr);
int len = static_cast<int>(env->CallIntMethod(bufList, listSize));
// load
IF_BOOL_EXEC(!g_clientSync, LOGE("[HIAI_DEMO_SYNC] Model Manager Client is nullptr."); return nullptr);
env->ReleaseStringUTFChars(modelpath, modelPath);
// run
LOGI("[HIAI_DEMO_SYNC] INPUT NCHW : %d %d %d %d.", inputDimension[0][0].GetNumber(),
inputDimension[0][0].GetChannel(), inputDimension[0][0].GetHeight(), inputDimension[0][0].GetWidth());
LOGI("[HIAI_DEMO_SYNC] OUTPUT NCHW : %d %d %d %d.", outputDimension[0][0].GetNumber(),
outputDimension[0][0].GetChannel(), outputDimension[0][0].GetHeight(), outputDimension[0][0].GetWidth());
runProcess(env, bufList, listGet, vecIndex, len, modelName);
// output_tensor
jclass output_list_class = env->FindClass("java/util/ArrayList");
jmethodID output_list_init = env->GetMethodID(output_list_class, "<init>", "()V");
jmethodID list_add = env->GetMethodID(output_list_class, "add", "(Ljava/lang/Object;)Z");
jobject output_list = env->NewObject(output_list_class, output_list_init, "");
long output_tensor_size = output_tensor[vecIndex].size();
LOGI("[HIAI_DEMO_SYNC] output_tensor_size is %ld .", output_tensor_size);
for (long j = 0; j < output_tensor_size; j++) {
float* outputBuffer = (float*)output_tensor[vecIndex][j]->GetBuffer();
int outputsize = outputDimension[vecIndex][j].GetNumber() * outputDimension[vecIndex][j].GetChannel() *
outputDimension[vecIndex][j].GetHeight() * outputDimension[vecIndex][j].GetWidth();
jfloatArray result = env->NewFloatArray(outputsize);
jfloat temp[outputsize];
for (int i = 0; i < outputsize; i++) {
temp[i] = outputBuffer[i];
}
env->SetFloatArrayRegion(result, 0, outputsize, temp);
jboolean output_add = env->CallBooleanMethod(output_list, list_add, result);
LOGI("[HIAI_DEMO_SYNC] output_add result is %d .", output_add);
}
env->ReleaseStringUTFChars(modelname, modelName);
return output_list;
}
Please follow this Docs integration.
Note : Only Huawei phones can be used. Other Huawei phones without the NPU cannot be used.
Related
How to send and parse JSON data through NRF24L01 sensor?
TRANSMITTER.ino (COM8 port) #include <SPI.h> #include <nRF24L01.h> #include <RF24.h> #include<ArduinoJson.h> RF24 radio(7, 8); // CE, CSN const byte addresses[6] = {"00001"}; void setup() { radio.begin(); radio.openWritingPipe(addresses); radio.setPALevel(RF24_PA_MIN); radio.stopListening(); } void loop() { DynamicJsonBuffer jBuffer; JsonObject& root = jBuffer.createObject(); root["North"] = "true"; root["South"] = "false"; root["East"] = "true"; root["West"] = "true"; radio.write(&root, sizeof(root)); delay(1000); } RECEIVER.ino (COM9 port) #include <SPI.h> #include <nRF24L01.h> #include <RF24.h> #include<ArduinoJson.h> RF24 radio(7, 8); // CE, CSN const byte addresses[6] = {"00001"}; void setup() { Serial.begin(9600); radio.begin(); radio.openReadingPipe(0, addresses); radio.setPALevel(RF24_PA_MIN); radio.startListening(); } void loop() { if ( radio.available()) { unsigned char data[1024]; radio.read(&data, sizeof(data)); StaticJsonBuffer<1024> jsonBuffer; JsonObject& toor = jsonBuffer.parseObject(data); String n = toor["North"]; String s = toor["South"]; String e = toor["East"]; String w = toor["West"]; Serial.println(n); Serial.println(s); Serial.println(e); Serial.println(w); delay(1000); } } I am trying to transmit a JSON data over NRF24L01, and printing it to the serial monitor, but i dont see any output in my serial monitor(COM9 serial monitor). what is the mistake am i doing here? I am using arduino JSON 5.13.5 version
Arduino + MySql + MySqlIO error when compiling
I'm trying to make this project. When i try to compile this code: #include <mysql.h> char *host, *user, *pass, *db; int isconnected = 0; void setup() { Serial.begin(9600); host = "localhost"; user = "root"; pass = ""; db = "arduino"; isconnected = mysql_connect(host,user,pass,db); if(isconnected){ Serial.print("Connected to "); Serial.println(host); } else{ Serial.println("Connection failed."); } mysql_close(); } void loop(){} Maybe problem is with libraries or Arduino IDE. I get these errors and warnings: C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino: In function 'void setup()': C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:30:7: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings] host = "localhost"; ^ C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:31:7: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings] user = "root"; ^ C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:32:7: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings] pass = ""; ^ C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:33:5: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings] db = "arduino"; ^ C:\Users\Mateusz\Documents\Arduino\libraries\mysql\mysql.cpp: In function 'String mysql_result_query(String, String)': C:\Users\Mateusz\Documents\Arduino\libraries\mysql\mysql.cpp:67:10: error: converting to 'String' from initializer list would use explicit constructor 'String::String(int, unsigned char)' return 0; ^ C:\Users\Mateusz\Documents\Arduino\libraries\mysql\mysql.cpp:71:10: error: converting to 'String' from initializer list would use explicit constructor 'String::String(int, unsigned char)' return 0; ^ exit status 1 Edit: There is library mysql.cpp. #include "mysql.h" int mysql_connect(char *host, char *user, char *pass, char *db){ Serial.print("host="); Serial.println(host); Serial.print("user="); Serial.println(user); Serial.print("pass="); Serial.println(pass); Serial.print("db="); Serial.println(db); Serial.println("mysql_connect()"); int x = Serial.read(); if(x == '-') return 0; while( x <= 0){ x = Serial.read(); if(x == '-') return 0; } return x-48; } int is_mysql(){ Serial.print("is_mysql()"); int x = Serial.read(); if(x == '-') return 0; while( x <= 0){ x = Serial.read(); if(x == '-') return 0; } return x-48; } void mysql_close(){ Serial.println("mysql_close()"); } int mysql_query(char *query){ Serial.print("query="); Serial.println(query); int x = Serial.read(); if(x == '-' || x == '0') return 0; while( x <= 0){ x = Serial.read(); if(x == '-' || x == '0') return 0; } return x-12; } String mysql_result_query(String query, String field){ String res = ""; String q = "query=" + query + "&field=" + field; Serial.println(q); res = Serial.readString(); if(res == "-") return 0; while(res.length() <= 0){ res = Serial.readString(); if(res == "-") return 0; } return res; } And there is mysql.h: #ifndef mysql_h #define mysql_h #include "Arduino.h" int mysql_connect(char *, char *, char *, char *); void mysql_close(); int is_mysql(); int mysql_query(char *); String mysql_result_query(String, String); #endif I don't know how to solve this. I could'nt find any solutions. Sorry for my english :)
You need to initialize your variables at the beginning. Try this: #include <mysql.h> char *host = "localhost", *user="root", *pass="", *db="arduino"; int isconnected = 0; void setup() { Serial.begin(9600); isconnected = mysql_connect(host,user,pass,db); if(isconnected){ Serial.print("Connected to "); Serial.println(host); } else{ Serial.println("Connection failed."); } mysql_close(); } void loop(){} The erros are comming from your mysql_result_query function. You are returning 0 for a function that returns a String. Try this. String mysql_result_query(String query, String field){ String res = ""; String q = "query=" + query + "&field=" + field; Serial.println(q); res = Serial.readString(); if(res == "-") return ""; while(res.length() <= 0){ res = Serial.readString(); if(res == "-") return ""; } return res; } Here I'm returning an empty string. You can check it later with the length() method.
Error memcpy in device code
I write a code that get first _var positions of a vector of possibilities (i.e., matrix _size*_var with _var=3 and _size=27) and calling this function in my kernel (32 threads, ie, each has an object) but I do not get any return value of the function neither the NULL pointer. The program exit without error but the printf lines in the kernel is not executed or displayed (even compiled with sm_20 or higher) as if the program stopped before. dataIntern.h: #include <math.h> #include <stdlib.h> #include <stdio.h> #define _MIN -1 #define _MAX 1 #ifdef __CUDACC__ #define CUDA_CALLABLE_MEMBER __host__ __device__ #else #define CUDA_CALLABLE_MEMBER #endif template <class a_type> class dataIntern{ private: a_type *possibilities; int _assign; int _size; int _var; int _maxsize; public: CUDA_CALLABLE_MEMBER dataIntern(){ } CUDA_CALLABLE_MEMBER dataIntern(int var){ _var = var; _size = (int)pow(3.0, (double)_var); _maxsize = _size * _var; _assign = 1; possibilities = (a_type*)malloc(_maxsize*sizeof(a_type)); if(!possibilities){ exit(1); } createTable(); } CUDA_CALLABLE_MEMBER void createTable(){ int i, j, k, limit, pos; a_type value; if(_assign == 1){ for(i=0; i<_var; i++){ #ifdef __CUDA_ARCH__ limit = (int)pow(3.0, _var-i-1); #else limit = (int)pow(3.0, (double)_var-i-1); #endif value = (a_type)_MIN; k = 0; for(j=0; j<_size; j++){ pos = _var*j+i; if(k >= limit){ value++; if(value > _MAX){ value = (a_type)_MIN; } k = 0; } possibilities[pos] = value; k++; } } } } CUDA_CALLABLE_MEMBER void print(){ int i; printf("Printing.\n"); if(_assign == 1){ for(i=0; i<_size*_var; i++){ printf("%d ", possibilities[i]); if(i%_var == _var-1){ printf("\n"); } } } else{ printf("Not assigned.\n"); } } CUDA_CALLABLE_MEMBER void retify(int posChanged, a_type valueRetified){ int i, pos, count, initpos, attrib; a_type *newnode; a_type *newlist = NULL, *morelist = NULL; pos = posChanged; initpos = 0; count = 0; if(_assign == 1){ attrib = 0; newnode = (a_type*)malloc(_var*sizeof(a_type)); for(i=0; i<_size; i++){ if(possibilities[pos] == valueRetified){ memcpy(newnode, &possibilities[i*_var], _var*sizeof(a_type)); count++; if(newlist!=NULL){ morelist = (a_type*)malloc(count*_var*sizeof(a_type)); memcpy(morelist, newlist, (count-1)*_var*sizeof(a_type)); } newlist = (a_type*)malloc(count*_var*sizeof(a_type)); memcpy(newlist, morelist, (count-1)*_var*sizeof(a_type)); memcpy(&newlist[initpos], newnode, _var*sizeof(a_type)); initpos+=_var; attrib = 1; } pos+=_var; } if(attrib == 1){ _size = count; possibilities = (a_type*)malloc(_size*_var*sizeof(a_type)); if(possibilities == NULL){ printf("Allocation fail in newlist retify.\n"); exit(1); } memcpy(possibilities, newlist, _size*_var*sizeof(a_type)); } else{ _assign = 0; } } } CUDA_CALLABLE_MEMBER a_type* unstack(){ a_type* solution = NULL, *backup = NULL; if(_assign == 1){ if(_size>0){ backup = (a_type*)malloc(_var*_size*sizeof(a_type)); if(backup == NULL){ printf("Erro to alloc backup pointer on unstack function in data intern\n"); return NULL; } solution = (a_type*)malloc(_var*sizeof(a_type)); if(solution == NULL){ printf("Erro to alloc solution pointer on unstack function in data intern\n"); return NULL; } memcpy(backup, possibilities, _size*_var*sizeof(a_type)); memcpy(solution, possibilities, _var*sizeof(a_type)); free(possibilities); _size--; possibilities = (a_type*)malloc(_size*_var*sizeof(a_type)); if(possibilities == NULL){ printf("Error to realloc possibilities pointer in data intern\n"); return NULL; } memcpy(possibilities, &backup[_var], _size*_var*sizeof(a_type)); free(backup); return solution; } } return NULL; } CUDA_CALLABLE_MEMBER int get_size(){ return _size; } CUDA_CALLABLE_MEMBER ~dataIntern(){ _assign = 0; if(possibilities) free(possibilities); } }; deviceCode.h: #ifndef DEVICECODE_H #define DEVICECODE_H void CallingInMain(); __global__ void kernel(); #endif deviceCode.cu: #include "deviceCode.h" #include "dataIntern.h" #include <iostream> #include <stdio.h> //I declared like this to my kernel: __global__ void kernel(){ __shared__ dataIntern<int> data[32]; int *vetor; vetor = NULL; data[threadIdx.x] = dataIntern<int>(3); //_var == 3 in the class above vetor = (int*)malloc(sizeof(int)*3); vetor = data[threadIdx.x].unstack(); while(vetor!=NULL){ //never past here printf("%d %d %d %d\n", threadIdx.x, vetor[0], vetor[1], vetor[2]); vetor = data[threadIdx.x].unstack(); } //neither here in if or else if(vetor) printf("Not null\n"); else printf("Null final\n"); free(vetor); } void CallingInMain(){ kernel<<<1, 32>>>(); cudaDeviceSynchronize(); } main.cu: #include <iostream> #include <stdio.h> #ifndef deviceCode_H #include "deviceCode.h" #endif int main(int argc, char* argv[]){ CallingInMain(); return 0; }
Some colleagues pointed out to me that your code seems to have an error in it. Consider this line in your kernel: data[threadIdx.x] = dataIntern<int>(3); This line instantiates a temporary dataIntern<int> object, runs the constructor with a value of 3 on it, and then does a copy from that object to the storage in data[threadIdx.x]. Note that the constructor performs a malloc operation: CUDA_CALLABLE_MEMBER dataIntern(int var){ ... possibilities = (a_type*)malloc(_maxsize*sizeof(a_type)); But since the original object is temporary, the C++ standard allows the object to be deleted at the termination of the statement, i.e. at the semicolon here: data[threadIdx.x] = dataIntern<int>(3); ^ after the copy-construction process is complete. But the deletion of the object triggers the destructor, which does a free operation on possibilities: CUDA_CALLABLE_MEMBER ~dataIntern(){ _assign = 0; if(possibilities) free(possibilities); } Therefore usage of the pointer so allocated subsequent to this line of code: data[threadIdx.x] = dataIntern<int>(3); such as in unstack here: vetor = data[threadIdx.x].unstack(); will be invalid. This is a violation of C++ programming rules, and the error is not specific to CUDA.
mysql with c program
I wrote a program in c language with mysql. It does not work well. I create a connect function to help me connect mysql MYSQL *ts_mysql_connect(char *host, char *user, char *pass, char *database) { MYSQL *conn = mysql_init(NULL); fprintf(stderr, "[ts_mysql_connect] conn-> %ld\n", conn); if (!mysql_real_connect(conn, host, user, pass, database, 0, NULL, 0)){ fprintf(stderr, "%s\n", mysql_error(conn)); exit(1); } //set auto commit to false if (mysql_autocommit(conn, 0)) fprintf(stderr, "%s\n", "SET MYSQL autocommit to off faild!"); fprintf(stderr, "[ts_mysql_connect] conn-> %ld\n", conn); return conn; } and I use below the code below to call my function MYSQL *test; test = ts_mysql_connect(conf->run_conf->mysql_host, conf->run_conf->mysql_user, conf->run_conf->mysql_pass, conf->run_conf->mysql_database); conf->mysql_start = time(NULL); if (verbose) fprintf(stderr, "[ts_mysql_insert] mysql conn init at %ld\n", &test); exit(1); i donot know why ts_mysql_connect return different address of the conn. run log: [ts_mysql_connect] conn-> 140065527302336 [ts_mysql_connect] conn-> 140065527302336 [ts_mysql_insert] mysql conn init at -1946154816 So why MYSQL *conn in [ts_mysql_insert] and [ts_mysql_connect] have different address
You didn't declare the function prototype of ts_mysql_connect in the second program, so the compiler assumes that the function returns an int type. If you use -Wall directive to enable all warnings, you will see a warning message like this: warning: implicit declaration of function ‘ts_mysql_connect’
#include <stdio.h> #include <stdlib.h> #include <my_global.h> #include <mysql.h> MYSQL *DatabaseConnection; const char *ServerName = "192.168.1.12"; const char *User = "dbuser"; const char *Password = "dbpassword"; const char *Name = "test"; const char *DB_Socket_Path = "/var/run/mysqld/mysql.sock"; int execute_db_query(const char *sql_query) { MYSQL_RES *result = NULL; MYSQL_ROW row; int num_fields; int i; if (!DatabaseConnection) return -1; mysql_query(DatabaseConnection, sql_query); result = mysql_store_result(DatabaseConnection); if(result == NULL) { mysql_free_result(result); return -1; } if (!result->eof) { mysql_free_result(result); return -1; } num_fields = mysql_num_fields(result); int f_count = result->field_count; int index =1 ; while ((row = mysql_fetch_row(result))) { for (i = 0; i < num_fields; i++) { printf("%s ", row[i] ? row[i] : "NULL"); } printf("\n"); index++; } mysql_free_result(result); return 0; } void close_db_connection() { mysql_close(DatabaseConnection); mysql_library_end(); } int init_connect() { DatabaseConnection = mysql_init(NULL); printf("MySQL client version: %s\n", mysql_get_client_info()); if (!mysql_real_connect(DatabaseConnection, ServerName, User, Password, Name, 0, DB_Socket_Path, 0)) { puts(mysql_error(DatabaseConnection)); close_db_connection(); return -1; } printf("Host : %s \n", mysql_get_host_info(DatabaseConnection)); printf("Server : %s: \n", mysql_get_server_info(DatabaseConnection)); printf("Protocol : %d\n", mysql_get_proto_info(DatabaseConnection)); return 0; } int main(void) { puts("SQL Example"); init_connect() ; execute_db_query("select * from test"); return EXIT_SUCCESS; } I see you are using socket less connection so you can pass NULL in this case.
G++ no matching constructor for initialization
I have the following classes in a .h: class Register { int content; public: Register (); }reg; class Simulator { int op1, op2, initial_pos; Register RA, RB, RC, RD, PC, SP, FP; bool zero, neg; int mem[1024]; public: Simulator (int, int, const std::string); void Memdump (); void Exec_next (); }sim; and the definition for the simulator constructor is as follows: Simulator::Simulator (int i, int j, int k, std::string fname) { FILE* instructions; valA = 0; valB = 0; valC = 0; valP = 0; valE = 0; op1 = 0; op2 = 0; zero = false; neg = false; valid1 = false; valid2 = false; PC::content = 0; FP::content = j; SP::content = j; initial_pos = k; for (int i = 0; i < 1024; i++) mem[i] = 0; //Read input file if (instructions = fopen (filename, 'r') == NULL) { cout << "Error 404: file not found\n"; exit (404); } for (int i = 0; !feof (instructions); i++) fscanf (instructions, "%d\n", &(mem[i + initial_pos]) ); fclose (instructions); } but when i try to compile this code i get the following error message: ./TP1.h:45:2: error: no matching constructor for initialization of 'class Simulator' }sim; ^ ./TP1.h:42:3: note: candidate constructor not viable: requires 3 arguments, but 0 were provided Simulator (int, int, const std::string); ^ ./TP1.h:10:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided why isn't g++ finding the constructor?
Nevermind. I'm using 1 less argument than required.