VisualGDB. Expression must have pointer type - c++

I have just started using visualgdb
#include <string.h>
#include <jni.h>
#include <stdio.h>
int s_ButtonPressCounter = 0;
jstring
Java_com_visualgdb_example_AndroidProject1_AndroidProject1_stringFromJNI( JNIEnv* env,
jobject thiz )
{
char szBuf[512];
sprintf(szBuf, "You have pressed this huge button %d times", s_ButtonPressCounter++);
jstring str = (*env)->NewStringUTF(env, szBuf);
return str;
}
I have my intelissense show error log
Expression must have pointer type.
I tried to change it to env.NewStringUTF(szBuf) but the build comes to error.

Maybe, you should replace
jstring str = (*env)->NewStringUTF(env, szBuf);
with
jstring str = env->NewStringUTF(env, szBuf);
or with
jstring str = (*env).NewStringUTF(env, szBuf);

Related

Read/write to memory that was previously allocated via JNI

I use macros to allocate memory via JNI and then write to that memory.
#MacroAllocator
case class SomeCaseClass(a: Int, b: Int, c: Int)
3 * INT.BYTES = 12, so it means I need to allocate 12 bytes of memory.
I wrote a buffer that stores offheap objects. and if i already get address of buffer i can reuse that address to write/read.
typedef struct {
uint8_t *buf;
size_t size;
} buf_t;
via jni i'm allocating memory (assume it's at compile time)
JNIEXPORT jlong JNICALL Java_some_package_com_1alloc(JNIEnv *env, jobject self, jint size) {
globalenv = env;
buf_t buf;
buf_alloc(&buf, (size_t) size);
jlong buf_addr = (jlong)buf.buf;
return buf_addr;
}
and then i'm trying to write something to that buf, it's okay too (compile time too)
JNIEXPORT void JNICALL Java_some_package_com_1write_1int(JNIEnv *env, jobject self, jint value, jint idx, jlong buf_addr) {
globalenv = env;
uint8_t *buf = (uint8_t*) buf_addr;
write_int_to_buf_at(buf, idx, value);
return;
}
and when everything is done, i'm trying to read (runtime):
JNIEXPORT jint JNICALL Java_some_package_com_read_1int(JNIEnv *env, jobject self, jint idx, jlong buf_addr) {
globalenv = env;
uint8_t *buf = (uint8_t*)buf_addr;
int32_t value = read_int_in_buf_at(buf, (size_t) idx);
return value;
}
UPD: read_int_in_buf_at func impl
int32_t read_int_in_buf_at(uint8_t *buf, size_t idx) {
uint8_t b3 = buf[idx + 3];
uint8_t b2 = buf[idx + 2];
uint8_t b1 = buf[idx + 1];
uint8_t b0 = buf[idx];
return (b3 << 24) | ((b2 & 255) << 16) |
((b1 & 255) << 8) | (b0 & 255);
}
i get some weird results when trying to read: 0, 1234125360, -1342346458, etc.
Continuing from the comments, you have to keep in mind that Java_some_package_com_1alloc returns the address of allocated memory (buf.buf) NOT the buf_t struct itself.
This means your functions have to change accordingly:
JNIEXPORT void JNICALL Java_some_package_com_1write_1int(JNIEnv *env, jobject self, jint value, jint idx, jlong buf_addr) {
globalenv = env;
// The `jlong` value is the address of allocated memory
uint8_t *buf = (uint8_t*) buf_addr;
write_int_to_buf_at(buf, idx, value);
}
and the reader:
JNIEXPORT jint JNICALL Java_some_package_com_read_1int(JNIEnv *env, jobject self, jint idx, jlong buf_addr) {
globalenv = env;
uint8_t *buf = (uint8_t*) buf_addr;
int32_t value = read_int_in_buf_at(buf, (size_t) idx);
return value;
}

Jni not working

This is my Java code.
class NativePrompt {
private native String getInput(String prompt); //native method
static //static initializer code
{
System.loadLibrary("NativePrompt");
}
public static void main(String[] args)
{
NativePrompt NP = new NativePrompt();
String sName = NP.getInput("Enter your name: ");
System.out.println("Hello " + sName);
}
}
I'm using jdk1.7.0_17 .
This is my c++ code
#include "NativePrompt.h"
#include "jni.h"
#include "string"
#include "iostream"
#include "vector"
using namespace std;
/*
* Class: NativePrompt
* Method: getInput
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_NativePrompt_getInput
(JNIEnv *env, jobject obj, jstring prompt){
string sEntry;
const char *str;
str = env->GetStringUTFChars(prompt, NULL);
if (str == NULL) {
return env->NewStringUTF("");
}
else{
cout << str;
//Frees native string resources
env->ReleaseStringUTFChars(prompt, str);
//reads n-consecutive words from the
//keyboard and store them in string
getline(cin, sEntry);
return env->NewStringUTF(sEntry.c_str());
}
}
I run this program using the below comments.
javac NativePrompt.java
javah NativePrompt
g++ -o NativePrompt.so -shared -I /usr/lib/jvm/jdk1.7.0_17/include -I
/usr/lib/jvm/jdk1.7.0_17/include/linux NativePrompt.cpp
export LD_LIBRARY_PATH='/home/user/jniwork/'
java NativePrompt
Now I'm getting the below error. I don't know how to resolve it .
Exception in thread "main" java.lang.UnsatisfiedLinkError: no
NativePrompt in java.library.path at
java.lang.ClassLoader.loadLibrary(ClassLoader.java:1860) at
java.lang.Runtime.loadLibrary0(Runtime.java:845) at
java.lang.System.loadLibrary(System.java:1084) at
NativePrompt.(NativePrompt.java:5)
try launching your application like this:
java -Djava.library.path=/home/user/jniwork/ NativePrompt
and also before, rename your library from NativePrompt.so to libNativePrompt.so
Hope this helps you out.

FATAL ERROR in native method: Bad global or local ref passed to JNI

I have gotten this error when setting the -Xcheck:jni option, and calling my native method.
The error is :
FATAL ERROR in native method: Bad global or local ref passed to JNI
I shall paste the native method (C code) here, hope that anybody who knows what is wrong with this piece of code, will enlighten me. Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fns_data.h"
#include "fns_client.h"
#include "sockRW.h"
#include "/usr/local/include/jni.h"
#include "JNIiSearchLib.h"
#include "com_eds_wise_util_JNIiSearchLib.h"
JNIEXPORT jstring JNICALL
Java_com_eds_wise_util_JNIiSearchLib_jniFNSSearchClient (
JNIEnv *env, jobject obj, jstring jip_addr, jint jport_number,
jstring jfield, jstring jquery_str, jint jhitnum)
{
HitIds *hit_list = NULL;
hitListPktStruct *hitPkt = NULL;
int hit_number = 0;
int i = 0;
int fnsErrno = 0;
char *result_str = NULL;
jstring *rslt_str = NULL;
const char *cip_addr = NULL;
const char *cquery_str = NULL;
char errbuf[1024];
cip_addr = (*env)->GetStringUTFChars(env, jip_addr, 0);
if (cip_addr == NULL) {
return ((* env)->NewStringUTF (env, "Error: Cannot get IP address."));
}
cquery_str = (*env)->GetStringUTFChars(env, jquery_str, 0);
if (cquery_str == NULL) {
(*env)->ReleaseStringUTFChars (env, jip_addr, cip_addr);
(*env)->DeleteLocalRef(env, cip_addr);
return ((* env)->NewStringUTF (env, "Error: Cannot get query string."));
}
printf ("[Java_JNILib_jniFNSSearchClient] ipaddress[%s] portnumber[%d]"
" querystr[%s]\n\n", cip_addr, jport_number, cquery_str);
/* Search and get back the handler & total hits
*/
hit_list = fns_search_client0 (cip_addr, jport_number,
"PN", cquery_str, &hit_number);
/* Display total hits
*/
printf ("Total hits = %d\n", hit_number);
/* Enumerate every item in the result list and display them.
* The results are returned as a string to Java in the following manner:
*
* "[hitresult1|hitresult2|hitresult3|..|hitresultN]\0"
*
* where hitresultN = 94-byte record
*
* [+string94+|+string94]+stringTerminator
*/
printf ("malloc[%d]\n", (hit_number * 95) + 3);
result_str = malloc (((hit_number * 95)+3) * sizeof(char));
if (result_str == NULL) {
printf ("Out of memory, unable to malloc\n");
rslt_str = (* env)->NewStringUTF (env, "Error: Out of memory, unable to malloc");
if (hit_list) {
FREE_STRING (hit_list);
}
if (hitPkt) {
FREE_HITLIST_STRUCT (hitPkt);
}
(*env)->ReleaseStringUTFChars (env, jip_addr, cip_addr);
(*env)->ReleaseStringUTFChars (env, jquery_str, cquery_str);
(*env)->DeleteLocalRef(env, cip_addr);
(*env)->DeleteLocalRef(env, cquery_str);
fflush(stdout);
return (rslt_str);
}
sprintf (result_str, "[");
for (i = 0; i < hit_number; i++) {
strcat (result_str, hitPkt->docNameList[i]);
if (i != (hit_number - 1)) {
strcat (result_str, "|");
}
}
strcat (result_str, "]");
printf ("\n\nFNS search result:[From Library]\n");
printf ("%s\n\n",result_str);
/* free the handler
*/
if (hit_list) {
FREE_STRING (hit_list);
}
/* free the result lists
*/
if (hitPkt) {
FREE_HITLIST_STRUCT (hitPkt);
}
/* prepare stuff for Java
*/
rslt_str = (* env)->NewStringUTF (env, result_str);
/* free our memory
*/
if (result_str) {
free (result_str);
}
(*env)->ReleaseStringUTFChars (env, jip_addr, cip_addr);
(*env)->ReleaseStringUTFChars (env, jquery_str, cquery_str);
(*env)->DeleteLocalRef(env, cip_addr);
(*env)->DeleteLocalRef(env, cquery_str);
fflush(stdout);
return (rslt_str);
}
I wonder how this even compiles. jstring is a pointer type already, so yours
jstring *rslt_str = NULL;
is a pointer to pointer, and i wonder how the compiler can take it as retval for GetStringUTFChars and returning it from your native method altogether.

jni convert string to char array

Not familiar with c++, can someone help me add cmd to the myStr array and pass it to the main() function, here is what I have so far:
JNIEXPORT void JNICALL Java_my_package_JNIActivity_callCmdLine(
JNIEnv *env, jobject obj, jstring cmd)
{
const char *nativeString = env->GetStringUTFChars(cmd, 0);
env->ReleaseStringUTFChars(cmd, nativeString);
char * myStr [] = {"v", nativeString};
//int main(int argc, char *argv[])
main(1, myStr);
}
Well, don't release it before you're finished with it.
char * nativeString;
{ const char * _nativeString = env->GetStringUTFChars(cmd, 0);
nativeString = strdup (_nativeString);
env->ReleaseStringUTFChars(cmd, _nativeString);
}
char * myStr [] = {"v", nativeString};
main(1, myStr);
free (nativeString);
Why not taking advantage of objects to garantee deletion is done automatically...?
class ConvertStringHelper
{
public:
ConvertStringHelper( JNIEnv *env, jstring value )
{
m_str = env->GetStringUTFChars(value, 0);
m_value = &value;
m_env = env;
}
~ConvertStringHelper()
{
m_env->ReleaseStringUTFChars( *m_value, m_str);
}
jstring* m_value;
const char *m_str;
JNIEnv *m_env;
};
Then:
ConvertStringHelper helper( env, cmd );
const char* nativeStr = helper.m_str;
// nativeStr is valid in helper's scope and memory will be cleanly released when exiting the scope!

how to convert char array to wchar_t array?

char cmd[40];
driver = FuncGetDrive(driver);
sprintf_s(cmd, "%c:\\test.exe", driver);
I cannot use cmd in
sei.lpFile = cmad;
so,
how to convert char array to wchar_t array ?
Just use this:
static wchar_t* charToWChar(const char* text)
{
const size_t size = strlen(text) + 1;
wchar_t* wText = new wchar_t[size];
mbstowcs(wText, text, size);
return wText;
}
Don't forget to call delete [] wCharPtr on the return result when you're done, otherwise this is a memory leak waiting to happen if you keep calling this without clean-up. Or use a smart pointer like the below commenter suggests.
Or use standard strings, like as follows:
#include <cstdlib>
#include <cstring>
#include <string>
static std::wstring charToWString(const char* text)
{
const size_t size = std::strlen(text);
std::wstring wstr;
if (size > 0) {
wstr.resize(size);
std::mbstowcs(&wstr[0], text, size);
}
return wstr;
}
From MSDN:
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
using namespace System;
int main()
{
char *orig = "Hello, World!";
cout << orig << " (char *)" << endl;
// Convert to a wchar_t*
size_t origsize = strlen(orig) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
wcscat_s(wcstring, L" (wchar_t *)");
wcout << wcstring << endl;
}
From your example using swprintf_s would work
wchar_t wcmd[40];
driver = FuncGetDrive(driver);
swprintf_s(wcmd, "%C:\\test.exe", driver);
Note the C in %C has to be written with uppercase since driver is a normal char and not a wchar_t.
Passing your string to swprintf_s(wcmd,"%S",cmd) should also work