I have following test.pyx
cdef public class Foo[object Foo, type FooType]:
cdef public char* foo(self):
r = "Foo"
return r
cython compiles that code to test.h and test.c and everything looks fine, but I can't figure out how to create Foo object from C-code.
Even if I create it using Cython function:
cdef public Foo create_Foo():
return Foo()
I can't figure out how to invoke foo method.
Thanks.
That answer I've got in Cython User Group:
Public should probably be disallowed for methods, since calling the
functions directly would break subclassing. If you need to
invoke the method from C, write a wrapper function for each method
that takes the object as extra argument, and invoke the method. E.g.
cdef char *foo_wrapper(Foo obj):
return obj.foo()
It's inconvenient if you have many methods, so if you have control
over the design of Foo to begin with, don't use methods but use
functions instead.
Specify create_ foo as def or cpdef. cdef - ed functions are converted entirely in C Code and will not be exposed to the Python module.
Related
In a nutshell, I need help with the right use of unique_ptr and not with the library ArmNN. So, the next paragraph is just for contextualization.
I am adapting my current application to use the library ArmNN. More specifically, I am doing that through the use of the interface ICaffeParser.
At line 22 of this interface, we have this using definition to define a unique_ptr to the interface, that I believe is the "cause" of my problems.
using ICaffeParserPtr = std::unique_ptr<ICaffeParser, void(*)(ICaffeParser* parser)>;
I am quite sure my problem is the incorrect use of unique_ptr in my context, once I could make some successful tests with a more simple application.
My current code contains a class, let's call it MyClass:
namespace MYNAMESPACE {
class MyClass {
public:
MyClass() {
}
// a lot of functions
// a lot of attributes
private:
// a lot of functions
// a lot of attributes
}
}
In order to make use of the ArmNN library, I have created a new private attribute for MyClass:
armnnCaffeParser::ICaffeParserPtr myParser;
and instantiated myParser at MyClass() constructor:
MyClass::MyClass() {
myParser = armnnCaffeParser::ICaffeParser::Create();
}
Remembering ICaffeParserPtr is a unique_ptr (I think), now I have the following compiling error:
/my_path/src/detector.cpp: In constructor ‘MYNAMESPACE::MyClass::MyClass()’:
/my_path/src/detector.cpp:13:20: error: no matching function for call to ‘std::unique_ptr<armnnCaffeParser::ICaffeParser, void (*)(armnnCaffeParser::ICaffeParser*)>::unique_ptr()’
MyClass::MyClass() {
^
In file included from /usr/aarch64-linux-gnu/include/c++/7/bits/locale_conv.h:41:0,
from /usr/aarch64-linux-gnu/include/c++/7/locale:43,
from /usr/aarch64-linux-gnu/include/c++/7/iomanip:43,
from /usr/include/opencv2/flann/lsh_table.h:40,
from /usr/include/opencv2/flann/lsh_index.h:49,
from /usr/include/opencv2/flann/all_indices.h:42,
from /usr/include/opencv2/flann/flann_base.hpp:43,
from /usr/include/opencv2/flann.hpp:48,
from /usr/include/opencv2/opencv.hpp:62,
from /my_path/src/detector.hpp:11,
from /my_path/src/detector.cpp:1:
/usr/aarch64-linux-gnu/include/c++/7/bits/unique_ptr.h:255:2: note: candidate: template<class _Up, class> std::unique_ptr<_Tp, _Dp>::unique_ptr(std::auto_ptr<_Up>&&)
unique_ptr(auto_ptr<_Up>&& __u) noexcept;
/usr/aarch64-linux-gnu/include/c++/7/bits/unique_ptr.h:255:2: note: template argument deduction/substitution failed:
/my_path/src/detector.cpp:13:20: note: candidate expects 1 argument, 0 provided
MyClass::MyClass() {
^
The error happens because myParser is actually being default-initialized and then assigned on the constructor body of MyClass::MyClass().
Since a function pointer is passed as a custom deleter to std::unique_ptr to form the ICaffeParserPtr type, the default constructor for this particular instance of std::unique_ptr is disabled as per [unique.ptr.single.ctor].
In other words, ICaffeParserPtr, for safety reasons, cannot be default-initialized — which specific function to otherwise assign as its deleter on initialization?
To address this, you should always initialize class members at the member initializer list. In this case, initialize myParser as such:
MyClass::MyClass():
myParser(armnnCaffeParser::ICaffeParser::Create()) {}
This avoids calling the unavailable default constructor for std::unique_ptr, and is generally a better practice than assigning to class members in the constructor body.
I can`t alias method "dump" from Marshal module
#include "ruby.h"
VALUE Marshal = Qnil;
void Init_test(){
Marshal = rb_define_module("Marshal");
rb_define_alias(Marshal, "hal_dump", "dump");//No error, but don`t work
}
In ruby:
require './test'
p Marshal.methods.grep(/dump/).sort #[:dump]
How i can do alias?
Your C code is similar to the following Ruby code:
module Marshal
alias hal_dump dump
end
dump is a singleton method but also a private instance method (that combination is a so-called module function). You only define an alias of the private instance method.
p Marshal.private_instance_methods.grep(/dump/) # => [:dump, :hal_dump]
That's also why you don't get an error. However you want to define an alias of the singleton method. That can be done by opening the singleton class. A corrected Ruby version might look like this:
p Marshal.methods.grep(/dump/) # => [:dump]
class << Marshal
alias hal_dump dump
end
p Marshal.methods.grep(/dump/) # => [:dump, :hal_dump]
The MRI C API implements the rb_singleton_class() function. It returns the singleton class and can be used like this to fix your code:
rb_define_alias(rb_singleton_class(Marshal), "hal_dump", "dump");
I would like to create a new array with a given type from a class object in GWT.
What I mean is I would like to emulate the functionality of
java.lang.reflect.Array.newInstance(Class<?> componentClass, int size)
The reason I need this to occur is that I have a library which occasionally needs to do the following:
Class<?> cls = array.getClass();
Class<?> cmp = cls.getComponentType();
This works if I pass it an array class normally, but I can't dynamically create a new array from some arbitrary component type.
I am well aware of GWT's lack of reflection; I understand this. However, this seems feasible even given GWT's limited reflection. The reason I believe this is that in the implementation, there exists an inaccessible static method for creating a class object for an array.
Similarly, I understand the array methods to just be type-safe wrappers around JavaScript arrays, and so should be easily hackable, even if JSNI is required.
In reality, the more important thing would be getting the class object, I can work around not being able to make new arrays.
If you are cool with creating a seed array of the correct type, you can use jsni along with some knowledge of super-super-source to create arrays WITHOUT copying through ArrayList (I avoid java.util overhead like the plague):
public static native <T> T[] newArray(T[] seed, int length)
/*-{
return #com.google.gwt.lang.Array::createFrom([Ljava/lang/Object;I)(seed, length);
}-*/;
Where seed is a zero-length array of the correct type you want, and length is the length you want (although, in production mode, arrays don't really have upper bounds, it makes the [].length field work correctly).
The com.google.gwt.lang package is a set of core utilities used in the compiler for base emulation, and can be found in gwt-dev!com/google/gwt/dev/jjs/intrinsic/com/google/gwt/lang.
You can only use these classes through jsni calls, and only in production gwt code (use if GWT.isProdMode()). In general, if you only access the com.google.gwt.lang classes in super-source code, you are guaranteed to never leak references to classes that only exist in compiled javascript.
if (GWT.isProdMode()){
return newArray(seed, length);
}else{
return Array.newInstance(seed.getComponentType(), length);
}
Note, you'll probably need to super-source the java.lang.reflect.Array class to avoid gwt compiler error, which suggests you'll want to put your native helper method there. However, I can't help you more than this, as it would overstep the bounds of my work contract.
The way that I did a similar thing was to pass an empty, 0 length array to the constructor of the object that will want to create the array from.
public class Foo extends Bar<Baz> {
public Foo()
{
super(new Baz[0]);
}
...
}
Baz:
public abstract class Baz<T>
{
private T[] emptyArray;
public Baz(T[] emptyArray)
{
this.emptyArray = emptyArray;
}
...
}
In this case the Bar class can't directly create new T[10], but we can do this:
ArrayList<T> al = new ArrayList<T>();
// add the items you want etc
T[] theArray = al.toArray(emptyArray);
And you get your array in a typesafe way (otherwise in your call super(new Baz[0]); will cause a compiler error).
I had to do something similar, I found it was possible using the Guava library's ObjectArrays class. Instead of the class object it requires a reference to an existing array.
T[] newArray = ObjectArrays.newArray(oldArray, oldArray.length);
For implementing an array concatenation method, I also stepped into the issue of missing Array.newInstance-method.
It's still not implemented, but if you have an existing array you can use
Arrays.copyOf(T[] original, int newLength)
instead.
In php we can call static member functions using class objects. For example
class Human
{
public static function Speak()
{
echo "I am a human.";
}
}
$human = new Human();
$human->Speak();
What we would expect is that a static member function can only be called using the class name and not the class instance variable (object). But what i have seen while programming is that php allows calling a static member function using the class object also. Is there any practical use or some important reason that this feature has been provided in php ?
This feature exists in java and c++ also. Thanks Oli for pointing this out in your response.
This is the same as in other OO languages, such as C++ and Java. Why would you want the interpreter to prevent this?
UPDATE
My best guess for this (and this is only a guess) is "for convenience". In essence, why should the user of your class necessarily care whether a given member function is static or not? In some circumstances, this will certainly matter; in others, maybe not. I'm not saying this is a great justification, but it's all I can come up with!
it allows you to abstract from the particular definition of the method, so that for example if you had to turn it into a static one at some point, you don't have to rewrite all the method calls!
I can't answer for PHP, (or really for anything) but consider this hypothetical C++:
class base{
public:
static void speak(){cout<<"base\n";}
};
class sub :public base {
public:
static void speak(){cout<<"sub\n"; }
};
int _tmain(int argc, _TCHAR* argv[]){
base *base1 = new base();
base1->speak();
sub *sub1 = new sub();
sub1->speak();
base *sub2 = new sub();
sub2->speak();
((sub*)sub2)->speak();
}
The output would be:
base
sub
base
sub
I'm sure it could be useful... maybe helping you determine which class's static method you should call based on the object currently in hand.
Hi after refering to http://www.mono-project.com/Embedding_Mono
i can call methods from managed code by using mono_runtime_invoke.
Now i want to call a method in the managed code with a function pointer (or at least some pointer) as argument from native c code
managed code
public delegate void MyDelegate ();
//method i want to call from native code
public static MyDelegate mono_method(MyDelegate c_ptr)
{
//...do sth
return c_ptr;
}
native code
typedef void (*FUNC_PTR)();
FUNC_PTR my_fct_ptr = some_c_function;
//calling the managed method
MonoObject *result_of_mono_method =
mono_runtime_invoke(mono_method, NULL, my_fct_ptr, NULL);
edit: to point out the problem
how can i call
public static unsafe int* mono_method(int *c_ptr)
from native c code, without using dllImport.
You have several options.
One is to add an internal call that takes a IntPtr (the function pointer) and the arguments: you will then cast the pointer to the function pointer type and call it normally from C code.
Using something like libffi can help to overcome the limitation of having just one function pointer type, it depends how many you need, you didn't specify.
Another option is to use Reflection.Emit to build a dynamic method: in it you will use the calli IL instruction to invoke the function pointer directly.
I'm not exactly sure what you're trying to ask here, but this is the easiest way to do a call back.