logo
down
shadow

swig char ** as a pointer to a char *


swig char ** as a pointer to a char *

Content Index :

swig char ** as a pointer to a char *
Tag : python , By : bjorngylling
Date : November 26 2020, 03:01 PM

hope this fix your issue From the SWIG 3.0 documentation, near the end of §9.2.1 cpointer.i:
#include <string.h>
#include <stdlib.h>
#include "pointers.h"

void conc(char *str1, char *str2, char **res){
  *res = (char *)malloc(strlen(str1)+strlen(str2)+1);
  strcpy(*res,str1);
  strcat(*res,str2);
}
void conc(char *str1, char *str2, char **res);
%module pointers

%{
#include "pointers.h"
%}

// This input typemap declares that char** requires no input parameter.
// Instead, the address of a local char* is used to call the function.
%typemap(in,numinputs=0) char** (char* tmp) %{
    $1 = &tmp;
%}

// After the function is called, the char** parameter contains a malloc'ed char* pointer.
// Construct a Python Unicode object (I'm using Python 3) and append it to
// any existing return value for the wrapper.
%typemap(argout) char** (PyObject* obj) %{
    obj = PyUnicode_FromString(*$1);
    $result = SWIG_Python_AppendOutput($result,obj);
%}

// The malloc'ed pointer is no longer needed, so make sure it is freed.
%typemap(freearg) char** %{
    free(*$1);
%}

// Now that the typemap exists, let swig wrap the header.
%include "pointers.h"
import pointers
result = pointers.conc('Hello ','World!');
print(result)

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How do I use a pointer to char from SWIG, in Perl?


Tag : cpp , By : Mossy Breen
Date : March 29 2020, 07:55 AM
With these it helps Depending on the complexity of the C++ interface, it may be easier, faster, and more maintainable to skip SWIG and write the XS code yourself. XS&C++ is a bit of an arcane art. That's why there is Mattia Barbon's excellent ExtUtils::XSpp module on CPAN. It make wrapping C++ easy (and almost fun).
The ExtUtils::XSpp distribution includes a very simple (and contrived) example of a class that has a string (char*) and an integer member. Here's what the cut-down interface file could look like:
// This will be used to generate the XS MODULE line
%module{Object::WithIntAndString};

// Associate a perl class with a C++ class
%name{Object::WithIntAndString} class IntAndString
{
  // can be called in Perl as Object::WithIntAndString->new( ... );
  IntAndString();

  // Object::WithIntAndString->newIntAndString( ... );
  // %name can be used to assign methods a different name in Perl
  %name{newIntAndString} IntAndString( const char* str, int arg );

  // standard DESTROY method
  ~IntAndString();

  // Will be available from Perl given that the types appear in the typemap
  int GetInt();
  const char* GetString ();

  // SetValue is polymorphic. We want separate methods in Perl
  %name{SetString} void SetValue( const char* arg = NULL );
  %name{SetInt} void SetValue( int arg );
};

How does SWIG wrap buffer(char array) and pointer from C to Python?


Tag : python , By : socurious
Date : March 29 2020, 07:55 AM
this will help The problem is that SWIG is trying to wrap the buffer as a String in Python, which is not just a pointer. The synthesised assignment for next_ptr will allocate memory and make a string copy, not just do a pointer assignment. You can work around this in several ways.
The simplest is to use %extend to add a "reset buffer" method in Python:
%extend {
  void resetPtr() {
    $self->next_ptr=$self->buf;
  }
}
%apply void * { char *next };
%apply void * { char buf[ANY] };

Is it safe to cast an unsigned char* to char*, and treat the dereferenced pointer as if it really points to a char?


Tag : cpp , By : chawei
Date : March 29 2020, 07:55 AM
Hope that helps THIS MIGHT SURPRISE YOU,
but there's no such guarantee in the C++11 Standard (N3337), nor in the upcoming C++14 (N3797).
char unsigned * p1 = ...;
char          * p2 = reinterpret_cast<char *> (p1);

*p1 == *p2; // (1), not guaranteed to be true
*p1 = UCHAR_MAX;

*p1 == *p2; // (1)

swig python output parameter by reference of char** (char**&)


Tag : python , By : kema
Date : March 29 2020, 07:55 AM
I hope this helps you . I'm struggled with the c++ wrap for python using swig, what makes me stuck is the output parameter by reference of char** (a list of char*). , One issue is this line:
PyList_Append($result, PyUnicode_FromString( *$1[itoken] )); 
PyList_Append($result, PyUnicode_FromString( (*$1)[itoken] ));
#ifdef EXPORTS
#   define API __declspec(dllexport)
#else
#   define API __declspec(dllimport)
#endif

API void getKeys(const char **& keys, int& result_length);
#define EXPORTS
#include "dict.hpp"

API void getKeys(const char **& keys, int& result_length)
{
    result_length = 5;
    keys = new const char*[result_length];
    keys[0] = "abcd";
    keys[1] = "efgh";
    keys[2] = "ijkl";
    keys[3] = "mnop";
    keys[4] = "qrst";
}
%module dict

%{
#include "dict.hpp"
%}

%include <windows.i>

%typemap(in,numinputs=0) (const char**& keys,int& result_length) (char **temp, int len) %{
  $1 = &temp;
  $2 = &len;
%}

%typemap(argout) (const char**& keys,int& result_length) (PyObject* obj) %{
    obj = PyList_New(*$2);
    for (int itoken = 0; itoken < *$2; itoken++) {
        PyList_SET_ITEM(obj, itoken, PyUnicode_FromString( (*$1)[itoken] )); 
    }
    $result = SWIG_Python_AppendOutput($result,obj);
%}

%typemap(freearg) (const char**& keys,int& result_length) %{
    delete [] *$1;
%}

%include "dict.hpp"
Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import dict
>>> dict.getKeys()
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst']

C char pointer, char pointer copying char pointer. Whether it can be considered as a automatic / dynamic space creation


Tag : c , By : user143729
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • Pandas string search in list of dicts
  • Decryption from RSA encrypted string from sqlite is not the same
  • need of maximum value in int
  • a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
  • Display image of 2D Sinewaves in 3D
  • how to prevent a for loop from overwriting a dictionary?
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • I have a regex statement to pull all numbers out of a text file, but it only finds 77 out of the 81 numbers in the file
  • How do I create a dataframe of jobs and companies that includes hyperlinks?
  • Detect if user has clicked the 'maximized' button
  • Does flask_login automatically set the "next" argument?
  • Indents in python 3
  • How to create a pool of threads
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • How do I get LOAD_CLASSDEREF instruction after dis.dis?
  • Django - How to add items to Bootstrap dropdown?
  • Linear Regression - Does the below implementation of ridge regression finding coefficient term using gradient method is
  • How to drop all rows in pandas dataframe with negative values?
  • Most Efficient Way to Find Closest Date Between 2 Dataframes
  • Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments
  • Looping through a function
  • Create a plot for each unique ID
  • a thread python with 'while' got another thread never start
  • Solution from SciPy solve_ivp contains oscillations for a system of first-order ODEs
  • trigger python events driven by selenium controlled browser
  • Passing line-edits to a contextmanager to set validators
  • Python: globals().items() iterations try to change a dict
  • Is it possible to specify starting values for each parameter (instead of bounds) for scipy's differential evolution?
  • why datetime.now() and constructed datetime using all fields(like year,month...) of now has big timedelta?
  • MySQL multiple table UPDATE query using sqlalchemy core?
  • find if a semantic version is superset of of another version python
  • Type checking against dynamically created objects
  • Struggling with simple reverse function
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com