I want to retrieve global variable x I just set in Julia from my C application.
Here's the code I have so far:
#include <julia.h>
void SimpleExecute(char *command, char *resultVar, char* result) {
jl_eval_string(command);
jl_value_t *var = jl_get_global(jl_base_module, jl_symbol(resultVar));
const char *str = jl_string_ptr(var);
sprintf(result, "%s", str);
}
int main(int argc, char *argv[])
{
char* result = malloc(sizeof(char) * 1024);
jl_init();
//(void)jl_eval_string("println(sqrt(2.0))"); //works
(void)SimpleExecute("x=sqrt(2.0)", "x", result);
jl_atexit_hook(0);
return 0;
}
However debugger shows that var is still NULL after jl_get_global call. Why?
I followed this tutorial but it does not touch on arbitrary variable retrieval. Source code shows similar usage.
I think there are a few things going on here:
First, you need to use jl_main_module and not jl_base_module.
Second, you cannot use jl_string_ptr to get the string value of a integer or floating point value. You can either use x=string(sqrt(2.0)) as the command to run, or use jl_unbox_float64 as a function to unbox the value you get back from Julia.
#include <julia.h>
#include <stdio.h>
void SimpleExecute(char *command, char *resultVar, const char* result) {
jl_eval_string(command);
jl_value_t *var = jl_get_global(jl_main_module, jl_symbol(resultVar));
if (var && jl_is_string(var)) {
const char * str = jl_string_ptr(var);
printf("%s\n", str);
} else {
const double val = jl_unbox_float64(var);
printf("%f\n", val);
}
}
int main(int argc, char *argv[])
{
char* result = malloc(sizeof(char) * 1024);
jl_init();
// (void)jl_eval_string("println(sqrt(2.0))"); //works
(void)SimpleExecute("x = sqrt(2.0)", "x", result);
jl_atexit_hook(0);
return 0;
}
You can run this by modifying the following:
cc -I/Users/$USER/Applications/Julia-1.3.app/Contents/Resources/julia/include/julia/ -Wl,-rpath,/Users/$USER/Applications/Julia-1.3.app/Contents/Resources/julia/lib/ -L/Users/$USER/Applications/Julia-1.3.app/Contents/Resources/julia/lib/ -ljulia main.c -o main
Related
I need to know a way for use environment variables in the C programming language. How can I use and read them?
For example, read an environment variable or take the value of an environment variable and load it in another variable.
You can use following functions -
char * getenv (const char *name)-returns a string that is the value of the environment variable name.
char * secure_getenv (const char *name)
Read about some more functions here -http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access
Use the getenv function from stdlib.h. That's it!
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("test\n");
const char* s = getenv("PATH");
// If the environment variable doesn't exist, it returns NULL
printf("PATH :%s\n", (s != NULL) ? s : "getenv returned NULL");
printf("end test\n");
}
getenv:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char* my_env_var = getenv("MY_ENV_VAR");
if(my_env_var)
printf("Var found: %s", my_env_var );
else
printf("Var not found.");
return 0;
}
On windows, you would use GetEnvironmentVariable.
#include <stdio.h>
#include <winbase.h>
int main(int argc, char *argv[])
{
TCHAR buff[100] = T("");
DWORD resultLengthInCharacters = GetEnvironmentVariable(T("USERDOMAIN"), buff, 100);
if (resultLengthInCharacters > 0 && resultLengthInCharacters < 100) {
_tprintf(T("USERDOMAIN: %s\n"), buff);
} else if ( resultLengthInCharacters > 100) {
_tprintf(T("USERDOMAIN too long to store in buffer of length 100, try again with buffer length %lu\n"), resultLengthInCharacters);
} else {
// Error handling incomplete, should use GetLastError(),
// but typically:
_tprintf(T("USERDOMAIN is empty or not set in the Environment\n"));
}
return 0;
}
But if you are trying to get a standard path variable, you should use the SHGetFolderPath function with the right CSIDL variable (like from this question: How do I get the application data path in Windows using C++?)
Another way could be to use the global variable environ.
#include <stdio.h>
extern char** environ;
void main(int argc, char* argv[])
{
int i=0;
while(environ[i]!=NULL){
printf("%s\n",environ[i++]);
}
}
Why it is not working... It should be working, right? gcc have problem with this line, but why?
render_history(history, 2);
Sorry for bothering. I am just a beginner.
#include <stdio.h>
void render_history(char** history, const int entry);
int main()
{
char* history[3][4];
history[0][0] = "1234";
history[1][0] = "5678";
history[2][0] = "9012";
render_history(history, 2); //??
return 0;
}
void render_history(char** history, const int entry)
{
// print "9012"
}
gcc have problem with this line, but why?
Because the type is wrong. char* history[3][4]; can't be passed as char**. They are incompatible types.
Try something like:
#include <stdio.h>
void render_history(char* (*history)[4] , const int entry)
{
printf("%s\n", history[entry][0]);
}
int main()
{
char* history[3][4];
history[0][0] = "1234";
history[1][0] = "5678";
history[2][0] = "9012";
render_history(history, 2);
return 0;
}
As mentioned above double pointer not equal to 2D array.
You can also use pointer to pointer of char. char **history. And with this you have several option:
1) Use compound literals
#include <stdio.h>
void render_history(const char **history, const int entry)
{
printf("%s\n", history[entry]);
}
int main(void)
{
const char **history = (const char *[]) { "1234", "5678", "9012", NULL};
render_history(history, 2);
return 0;
}
If you need change your data later
2) Use dynamic memory allocation with malloc
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void render_history(char **history, const int entry)
{
printf("%s\n", history[entry]);
}
int main(void)
{
char **history = malloc(3 * sizeof(char *));
for (int i = 0; i < 3; ++i)
{
history[i] = malloc(4 * sizeof(char));
}
strcpy(history[0], "1234");
strcpy(history[1], "5678");
strcpy(history[2], "9012");
history[3] = NULL;
render_history(history, 2);
return 0;
}
If you use 2nd option dont forget free memory after use.
I need to pass a pre-allocated array of strings as a function parameter, and strcpy() to each of the strings within the string array, as in this example:
static void string_copy(char * pointer[]) {
strcpy(pointer[0], "Hello ");
strcpy(pointer[1], "world");
}
int main(int argc, const char * argv[]) {
char my_array[10][100];
string_copy(my_array);
printf("%s%s\n", my_array[0], my_array[1]);
}
And the resulting printed string would be 'Hello world'.
How do I pass a pre-allocated string array and fill out each string within a function as shown above?
When you are doing string_copy(my_array), you are passing a char (*)[100], i.e. pointer to char[100] array to your function. But your function is expecting a char *[], i.e. array of char pointers, because you have defined your function that way.
You can fix this by making changes so that your function (string_copy()) expects a char (*)[100], instead of a char *[].
For this, you can change your function definition as:
/* Your my_array gets converted to pointer to char[100]
so, you need to change your function parameter
from `char *pointer[]` to `char (*pointer)[100]`
*/
/* static void string_copy(char *pointer []) */
static void string_copy(char (*pointer) [100])
{
strcpy(pointer[0], "Hello ");
strcpy(pointer[1], "world");
}
* Alternative Solution *
A different design/solution would be to change in your main() function so that you are actually passing a char *[], which decays into a char ** - which is fine - to string_copy(). This way you would NOT have to change your string_copy() function.
int main(int argc, const char * argv[]) {
char my_array[10][100];
int tot_char_arrs, i;
char *char_arr_ptr[10];
/* Get total number of char arrays in my_array */
tot_char_arrs = sizeof(my_array) / sizeof(my_array[0]);
// Store all char *
for (i = 0; i < tot_char_arrs; i++)
char_arr_ptr[i] = my_array[i];
/* Actually passing a char *[].
it will decay into char **, which is fine
*/
string_copy(char_arr_ptr);
printf("%s%s\n", my_array[0], my_array[1]);
}
you need to use a pointer to the array. here is an example with 1 dimension array:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
static void string_copy(char **pointer) {
strcpy(pointer[0], "Hello ");
}
int main(int argc, const char * argv[]) {
char my_array[10];
char * p_array = my_array;
string_copy(&p_array);
printf("%s\n", my_array);
}
Your function can simply accept matrix dimensions and pass a const char * that stores the array of literals (pre-allocated) strings:
#include <stdio.h>
#include <string.h>
#define STRINGS_LENGTH 100
static void string_copy(size_t n, size_t m, char pointer[n][m], const char *strings_to_copy[])
{
for (size_t i=0; i< n; i++)
{
strcpy(pointer[i], strings_to_copy[i]);
}
}
int main( void )
{
const char *strings[] = { "hello", "World" };
char my_array[sizeof(strings)/sizeof(strings[0])][STRINGS_LENGTH];
string_copy(sizeof(strings)/sizeof(strings[0]), STRINGS_LENGTH, my_array, strings);
printf("%s %s\n", my_array[0], my_array[1]);
}
You can also change the structure of your code using dynamic allocation for your output array like:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
static bool string_copy(char *pointer[], const char *strings_to_copy[], size_t strings)
{
for (size_t i=0; i< strings; i++)
{
pointer[i] = malloc(strlen(strings_to_copy[i])+1);
if (pointer[i] != NULL)
strcpy(pointer[i], strings_to_copy[i]);
else
return false;
}
return true;
}
int main(void)
{
const char *strings[] = { "hello", "World" };
char *my_array[sizeof(strings)/sizeof(strings[0])] = {0};
if (string_copy(my_array, strings, sizeof(strings)/sizeof(strings[0])) )
{
printf("%s %s\n", my_array[0], my_array[1]);
}
for (size_t i = 0; i<sizeof(strings)/sizeof(strings[0]); i++)
free (my_array[i]);
}
#include <stdio.h>
#include <stdlib.h>
int countArrayChars(char *strArray[]){
int i=0;
while (strArray[i] != '\0'){
i++;
}
printf("%d\n", i);
return i;
}
int main(int argc, const char * argv[]) {
char *dog[] = {"dog"};
countArrayChars(dog);
For some reason, it prints "5".
Shouldn't it print 3?
I even tried to put \0 after the "g".
You declare array of string and initialize it with dog.
char *dog[] = {"dog"};
Actually it represented as
dog[0] = "Dog"; //In your case only element index with 0.
...............
...............
dog[n] = "tiger"; //If there Have n+1 element
Hence your array size is 1. Which hold constant string dog. To access it you should use dog[0].
So without less modification you can use your code as:
int countArrayChars(char *strArray[])
{
int i=0;
while (strArray[0][i] != '\0')
{
i++;
}
printf("%d\n", i);
return i;
}
int main(int argc, const char * argv[])
{
char *dog[] = {"dog"};
countArrayChars(dog);
}
Or if you want to declare a string use
char *dog = "dog";
or
char dog[] = "dog";
Please try this
#include <stdio.h>
#include <stdlib.h>
int countArrayChars(char *strArray){
int i=0;
while (strArray[i] != '\0'){
i++;
}
printf("%d\n", i);
return i;
}
int main(int argc, const char * argv[]) {
char *dog[] = "dog";
countArrayChars(dog);
}
This question already has answers here:
Assignment of function parameter has no effect outside the function
(2 answers)
Closed 9 years ago.
I am trying to understand why this statement doesn't work.
char resp[] = "123456789";
void getValue(char *im)
{
im = resp;
printf("\n%s\n",im);
}
int main(int argc, char *argv[])
{
char imei[11] = {0};
getValue(imei);
printf("\nIMEI: %s\n",imei);
return 0;
}
Output:
123456789
IMEI:
You can not assign with =, use strcpy instead:
#include <stdio.h>
#include <string.h>
char resp[] = "123456789";
void getValue(char *im)
{
im = strcpy(im, resp);
printf("\n%s\n",im);
}
int main(int argc, char *argv[])
{
char imei[11] = {0};
getValue(imei);
printf("\nIMEI: %s\n",imei);
return 0;
}
That's because imei is an array[11] (not just a pointer to), if you want to assign via = you can:
#include <stdio.h>
char resp[] = "123456789";
void getValue(char **im)
{
*im = resp;
printf("\n%s\n",*im);
}
int main(int argc, char *argv[])
{
char *imei; /* Not an array but a pointer */
getValue(&imei);
printf("\nIMEI: %s\n",imei);
return 0;
}
C passes parameters by value. Whatever change you ale to the im will be lost when the function exits. If you want to preserve the change. Pass the address of the pointer. Then you can change the pointer at the address you pass.
Try this:
char resp[] = "123456789";
void getValue(char **im)
{
*im = resp;
printf("\n%s\n",*im);
}
You need to pass a pointer to a pointer as your program argument.