?
Solved

Calling C library from C++ program

Posted on 2014-02-21
1
Medium Priority
?
436 Views
Last Modified: 2014-03-05
I have C++ based java native methods that works perfectly in passing String parameters back and forth with Java but wanted to know how could i load the C library from this C++ program and pass the parameters into it and get return string back from it.

The reason I want to not interact with C directly is because I need to pass 32 string parameters and handling them may be a challenge. If there is a easy way to handle 32 parameters in C  that will be great.
0
Comment
Question by:jgdvishnu
1 Comment
 
LVL 86

Accepted Solution

by:
jkr earned 1500 total points
ID: 39877819
You can call C libraries from C++ code just like other C++ libraries. E.g.

// lib.h

size_t get_string(char* buf, const size_t bufsz);

Open in new window


// lib.c

size_t get_string(char* buf, const size_t bufsz) {

  const char* pText = "This is my output";
  size_t len = strlen(pText);

  if (len  + 1 > bufsz) return 0; // not enough room

  strcpy(buf,pText);

  return len;
}

Open in new window


//usingclib.cpp
#include "lib.h"
#include <string>
#inlude <iostream>
// ...

  char str[255];
  std::string string_from_c_lib;

  if (0 < get_text(str,sizeof(str)) {

    string_from_c_lib = str;

    std::cout << "Got that from C lib: " << string_from_c_lib << std::endl;
  }

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
This video teaches viewers about errors in exception handling.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses
Course of the Month13 days, 10 hours left to enroll

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question