Global void*, making it pointer to structure pointer - pointers

I've something like:
struct list{
struct list **next, **prev;
}
Global declaration:
struct list *threads = &((struct list){&threads, &threads});
void* vp_threads; /Error here: previous declaration of 'vp_threads' was here
vp_threads = threads; //Error here: conflicting types for vp_threads
2nd way I tried:
void* vp_threads = threads; //Error: initializer element is not constant
I have to do this because ... (see below!)
void some_func()
{
add_head(vp_threads, ...)
...
}
void add_head(void* x, ...)
{ ... }
(PS: And there's not main() or initialization function, this's core.c file kind of, implementing all the functions which are in .h)
Why this's not working, I'm just trying to make void* to point to my structure. what's wrong with this?

try doing
vp_threads = threads;
in main ( or an initialization function )
you can't put a statement in global scope. your statement vp_threads = threads; would have to live inside a function somewhere

Related

shared_ptr not changing object (Visual studio 2012)

I have a really strange problem. I can't modify the object I am pointing to with a shared_ptr.
Example code:
#include<memory>
#include<iostream>
using namespace std;
class foo
{
public:
int asd;
foo(){}
~foo(){}
};
void d(shared_ptr<foo> c)
{
c->asd = 3;
}
void main()
{
foo a;
a.asd = 5;
d(make_shared<foo>(a));
cout<<a.asd; //asd is still 5
}
As far as I know you can access the object pointed to by the shared_ptr by using the "->" operator, so what am I doing wrong here? How can I change the asd variable inside the class via the shared pointer?
// create a temporary object by copying a
// the shared pointer you pass to d function actually points to this temporary object
d(make_shared<foo>(a));
// allocate and store foo object in shared_ptr instead
auto p_a(make_shared<foo>());
p_a->asd = 3;
d(p_a);
... so what am I doing wrong here?
From cppreference on std::make_shared [emphasis mine]:
template< class T, class... Args >
shared_ptr<T> make_shared( Args&&... args );
Constructs an object of type T and wraps it in a std::shared_ptr
using args as the parameter list for the constructor of T.
In your case, you supply an instance of foo as argument to std::make_shared, which will be used when constructing a new object of type foo; i.e., making use of the default supplied copy CTOR of foo (foo(const foo&)). This new object will be a temporary and only live for the call to d(...).

c - Array of pointer to functions, having different number of arguments

I am making a simple scheduler that executes functions contained in a FIFO queue.
Those functions have a same return type int, but have different number of int arguments.
I tried to implement it this way, but it does not seem to work. The compiler forbids conversion between int(*)() , int(*)(int), int(*)(int, int), or to any of those sort. (Arduino Sketch compiler)
Is there a way to solve this problem, or could you recommend a better way around? Thanks!
My code:
typedef int (*fnptr)(); // Tried this!
int foo(int var) {
return 0;
}
int main() {
fnptr fp = &foo; // error: invalid conversion from
// 'int (*)(int)' to 'int (*)()'
// [-fpermissive]
return 0;
}
You can cast:
fnptr fp = reinterpret_cast<fnptr>(foo);
The ()s are the "function call operator", adding them makes no sense at all in this situation, it changes the expression from "take the address of this function" to "take the address of this function's return value".
Note that aboev I don't even include the &, this is because the name of a function acts pretty much like a function pointer so it's already an address.

Can R extension safely allocate memory when it comes to exceptional conditions?

I am about to write an extension package for R in C++ and wonder how dynamic memory management is intended to be used without risk of memory leaks. I have read
http://cran.r-project.org/doc/manuals/R-exts.html#Memory-allocation
http://cran.r-project.org/doc/manuals/R-exts.html#Garbage-Collection
and immediately get to three questions:
Does R gracefully unwind the C++ stack frame in case of R-exceptions, e.g. when R_alloc runs out of memory or Rf_error is called due to some other condition? – Otherwise, how am I supposed to clean up already R_alloc'ed and PROTECTed or simply Calloc'ed memory? For example, will
#include<R.h>
// […]
void someMethod () {
char *buffer1 = NULL;
char *buffer2 = NULL;
try {
ClassA a;
buffer1 = R_Calloc( 10000, char );
buffer2 = R_Calloc( 10000, char );
// […]
} finally {
try {
if ( NULL != buffer1 ) {
R_Free( buffer1 );
}
} finally {
if ( NULL != buffer2 ) {
R_Free( buffer2 );
}
}
}
}
guarantee to call the destructor ~ClassA for a and R_Free for buffer1 and buffer2? And if not, what would be the R textbook way to guarantee that?
Could standard C++ (nowadays deprecated) std::auto_ptr or modern std::unique_ptr be employed to simplify the memory allocation idiom?
Is there a proven C++ idiom/best practice to use R's memory allocation in the C++ standard template library, e.g. some suitable allocator template, so that STL classes allocate their memory from the R heap?
Since Rf_error will indeed skip the C++ stack frame and thus bypass destructor calls, I found it necessary to undertake more documentation research. In particular a look into the RODBC package and experimentation monitoring memory use to confirm the findings, made me arrive at:
1: Immediately store pointer in an R external pointer and register a finaliser for that.
The idiom is illustrated in the following somewhat simplistic example:
#define STRICT_R_HEADERS true
#include <string>
#include <R.h>
#include <Rinternals.h> // defines SEXP
using namespace std;
class A {
string name;
public:
A ( const char * const name ) : name( name ) { Rprintf( "Construct %s\n", name ); }
~A () { Rprintf( "Destruct %s\n", name.c_str() ); }
const char* whoami () const { return name.c_str(); }
};
extern "C" {
void finaliseAhandle ( SEXP handle ) {
A* pointer = static_cast<A*>( R_ExternalPtrAddr( handle ) );
if ( NULL != pointer ) {
pointer->~A();
R_Free( pointer );
R_ClearExternalPtr( handle );
}
}
SEXP createAhandle ( const SEXP name ) {
A* pointer = R_Calloc( 1, A );
SEXP handle = PROTECT( R_MakeExternalPtr(
pointer,
R_NilValue, // for this simple example no use of tag and prot
R_NilValue
) );
try {
new(pointer) A( CHAR( STRING_ELT( name, 0 ) ) );
R_RegisterCFinalizerEx( handle, finaliseAhandle, TRUE );
} catch (...) {
R_Free( pointer );
R_ClearExternalPtr( handle );
Rf_error( "construction of A(\"%s\") failed", CHAR( STRING_ELT( name, 0 ) ) );
}
// … more code may follow here, including calls to Rf_error.
UNPROTECT(1);
return handle;
}
SEXP nameAhandle ( const SEXP handle ) {
A* pointer = static_cast<A*>( R_ExternalPtrAddr( handle ) );
if( NULL != pointer ) {
return mkChar( pointer->whoami() );
}
return R_NilValue;
}
SEXP destroyAhandle ( const SEXP handle ) {
if( NULL != R_ExternalPtrAddr( handle ) ) {
finaliseAhandle( handle );
}
return R_NilValue;
}
}
The assignment of NULL to the pointer in R_ClearExternalPtr( handle ); prevents double calling of R_Free( pointer );`.
Mind that there is still some assumption needed for the suggested idiom to safely work: If the constructor must not fail in the sense of R, i.e. by calling Rf_error. If this cannot be avoided, my advice would be to postpone the constructor invocation to after the finaliser registration so that the finaliser will in any case be able to R_Free the memory. However, logic must be included in order not to call the destructor ~A unless the A object has been validly constructed. In easy cases, e.g. when A comprises only primitive fields, this may not be an issue, but in more complicated cases, I suggest to wrap A into a struct which can then remember whether the A constructor completed successfully, and then allocate memory for that struct. Of course, we must still rely on the A constructor to gracefully fail, freeing all memory it had allocated, regardless of whether this was done by C_alloc or malloc or the like. (Experimentation showed that memory from R_alloc is automatically freed in case of Rf_error.)
2: No.
Neither class has anything to do with registering R external pointer finalisers.
3: Yes.
As far as I have seen, it is considered best practice to cleanly separate the reigns of C++ and R. Rcpp encourages the use of wrappers (https://stat.ethz.ch/pipermail/r-devel/2010-May/057387.html, cxxfunction in http://dirk.eddelbuettel.com/code/rcpp.html) so that C++ exceptions will not hit the R engine.
In my opinion, an allocator could be programmed to use R_Calloc and R_Free. However, to counter the effects of potential Rf_error during such calls, the allocator would require some interface to garbage collection. I imagine locally tying the allocator to a PROTECTed SEXP of type externalptr which has a finaliser registered by R_RegisterCFinalizerEx and points to a local memory manager which can free memory in case of Rf_error.

the implementation of FileIO::Read()

when i read the source code of fileIO::read().I came across a problem.
First of all,the fileIO::Read() source code is:
enter int32_t FileIO::Read(int64_t offset,
char* buffer,
int32_t bytes_to_read,
const CompletionCallback& cc)
{
if (has_interface<PPB_FileIO_1_1>()) {
return get_interface<PPB_FileIO_1_1>()->Read(pp_resource(),
offset, buffer, bytes_to_read, cc.pp_completion_callback());
} else if (has_interface<PPB_FileIO_1_0>()) {
return get_interface<PPB_FileIO_1_0>()->Read(pp_resource(),
offset, buffer, bytes_to_read, cc.pp_completion_callback());
}
return cc.MayForce(PP_ERROR_NOINTERFACE);
}
we can see that across get_interface(),we get a Func Pointer.the problem is, how to get this pointer.
then i find the source code of get_interface:
template <typename T> inline T const* get_interface() {
static T const* funcs = reinterpret_cast<T const*>(
pp::Module::Get()->GetBrowserInterface(interface_name<T>()));
return funcs;
}
and then the source code of GetBrowserInterface(),
const void* Module::GetBrowserInterface(const char* interface_name) {
return get_browser_interface_(interface_name);
}
Module::Module() : pp_module_(0), get_browser_interface_(NULL), core_(NULL){}
we can see that when construct the Module,we set the get_browser_interface_ to NULL,and i find nowhere that InternalInit() Func wasn't called at all.
so it Confuses that how to get the Read() Pointer.And where are the source code of the implemention of Read()? thank you.
pp::Module::InternalInit is called in ppp_entrypoints.cc. The functions in this file are called as the entrypoint to the PPAPI Native Client module when you link in the ppapi_cpp library.
Specifically, PPP_InitializeModule is called by the module loader to initialize the Native Client module.
The source code of PPB_FileIO_1_1::Read can be found in the ppapi library here. This forwards to the proxy here.

CLI/C++: void* to System::Object

This is a similar question to this SO post, which I have been unable to use to solve my problem. I have included some code here, which will hopefully help someone to bring home the message that the other posting was getting at.
I want to write a CLI/C++ method that can take a void pointer as a parameter and return the managed object (whose type I know) that it points to. I have a managed struct:
public ref struct ManagedStruct { double a; double b;};
The method I am trying to write, which takes a void pointer to the managed struct as a parameter and returns the struct.
ManagedStruct^ VoidPointerToObject(void* data)
{
Object^ result = Marshal::PtrToStructure(IntPtr(data), Object::typeid);
return (ManagedStruct^)result;
}
The method is called here:
int main(array<System::String ^> ^args)
{
// The instance of the managed type is created:
ManagedStruct^ myData = gcnew ManagedStruct();
myData->a = 1; myData->b = 2;
// Suppose there was a void pointer that pointed to this managed struct
void* voidPtr = &myData;
//A method to return the original struct from the void pointer
Object^ result = VoidPointerToObject(voidPtr);
return 0;
}
It crashes in the VoidPointerToObject method on calling PtrToStructure , with the error: The specified structure must be blittable or have layout information
I know this is an odd thing to do, but it is a situation I have encountered a few times, especially when unmanaged code makes a callback to managed code and passes a void* as a parameter.
(original explanation below)
If you need to pass a managed handle as a void* through native code, you should use
void* voidPtr = GCHandle::ToIntPtr(GCHandle::Alloc(o)).ToPointer();
// ...
GCHandle h = GCHandle::FromIntPtr(IntPtr(voidPtr));
Object^ result = h.Target;
h.Free();
(or use the C++/CLI helper class gcroot)
Marshal::PtrToStructure works on value types.
In C++/CLI, that means value class or value struct. You are using ref struct, which is a reference type despite use of the keyword struct.
A related problem:
void* voidPtr = &myData;
doesn't point to the object, it points to the handle.
In order to create a native pointer to data on the managed heap, you need to use pinning. For this reason, conversion between void* and Object^ isn't as useful as first glance suggests.

Resources