How to get thrust::pair first and second use javacpp - thrust

From https://github.com/bytedeco/javacpp/wiki/Interface-Thrust-and-CUDA, I write thrust java code. Struct field is public by default, but I use first() method to get the first field value of thrust::pair, error happen.
error: expression preceding parentheses of apparent call must have (pointer-to-) function type
error: macro "offsetof" passed 3 arguments, but takes just 2
{ sizeof(thrust::pair), offsetof(thrust::pair, first) },
So how to get thrust::pair first and second value ?
#Platform(include="<thrust/pair.h>")
#Namespace("thrust")
public class Thrust {
static { Loader.load(); }
#Name("pair<int, double>")
public static class Pair extends Pointer {
static { Loader.load(); }
public Pair(IntPointer key, DoublePointer value){
allocate(key, value);
}
private native void allocate(#ByRef IntPointer k, #ByRef DoublePointer v);
// will happen error: expression preceding parentheses of apparent call must have (pointer-to-) function type
public native IntPointer first();
// will happen error: macro "offsetof" passed 3 arguments, but takes just 2
{ sizeof(thrust::pair<int, double>), offsetof(thrust::pair<int, double>, first) },
public native Pair first(IntPointer p);
}
public static void main(String[] args) {
IntPointer i = new IntPointer(1);
i.put(10);
DoublePointer d = new DoublePointer(1);
d.put(10.0);
Pair p = new Pair(i, d);
System.out.println(p.first());
}
}

Related

How can I solve 'Duplicate Constructor' error in Haxe?

In Haxe, I created a class named MyClass like:
class MyClass {
var score: String;
public function new (score: Int) {
this.score = Std.string(score);
}
public function new (score: String) {
this.score = score;
}
}
I need multiple constructors but Haxe does not allow me to do. It throws this error from building phase:
*.hx:*: lines * : Duplicate constructor
The terminal process terminated with exit code: 1
How can I solve this problem?
This is known as method overloading, which is not supported by Haxe apart from externs (but might be in the future). There's multiple ways you could work around this.
A common workaround in the case of constructors would be to have a static "factory method" for the second constructor:
class MyClass {
var score:String;
public function new(score:String) {
this.score = score;
}
public static function fromInt(score:Int):MyClass {
return new MyClass(Std.string(score));
}
}
You could also have a single constructor that accepts both kinds of arguments:
class MyClass {
var score:String;
public function new(score:haxe.extern.EitherType<String, Int>) {
// technically there's no need for an if-else in this particular case, since there's
// no harm in calling `Std.string()` on something that's already a string
if (Std.is(score, String)) {
this.score = score;
} else {
this.score = Std.string(score);
}
}
}
However, I wouldn't recommend this approach, haxe.extern.EitherType is essentially Dynamic under the hood, which is bad for type safety and performance. Also, EitherType is technically only intended to be used on externs.
A more type-safe, but also slightly more verbose option would be haxe.ds.Either<String, Int>. Here you'd have to explicitly call the enum constructors: new MyClass(Left("100")) / new MyClass(Right(100)), and then use pattern matching to extract the value.
An abstract type that supports implicit conversions from String and Int might also be an option:
class Test {
static function main() {
var s1:Score = "100";
var s2:Score = 100;
}
}
abstract Score(String) from String {
#:from static function fromInt(i:Int):Score {
return Std.string(i);
}
}
Finally, there's also an experimental library that adds overloading support with macros, but I'm not sure if it supports constructors.
I recommend to use type parameter
class MyClass<T> {
var score:String;
public function new(score:T) {
this.score = Std.string(score);
}
}
You can also use type parameter at constructor
class MyClass {
var score:String;
public function new<T>(score:T) {
this.score = Std.string(score);
}
}
However, T used at constructor fails at runtime (CS and Java), it is not fixed yet (Haxe 4). Otherwise, you could do this
class MyClass {
var score:String;
#:generic public function new<#:const T>(score:T) {
this.score = Std.is(T, String) ? untyped score : Std.string(score);
}
}
which nicely produce code like this (CS)
__hx_this.score = ( (( T is string )) ? (score) : (global::Std.#string(score)) );
causing Std.string() to be called only if T is not a String.
Hej,
With a simple example as it is, you can just do something like that function new( ?s : String, ?n : Int ){} and Haxe will use the correct argument by type. But you'll be able to do new() and maybe you don't want.

How to initialize c++/cx class with aggregate initialization?

I have this ref class:
namespace N
{
public ref class S sealed
{
public:
property Platform::String^ x;
};
}
How do I initialize it in place with the aggregate initializer?
I have tried:
N::S s1 = { %Platform::String(L"text") };
but the compiler says
error C2440: 'initializing': cannot convert from 'initializer list' to
'N::S'
Also:
N::S s1 { %Platform::String(L"text") };
and the error is:
error C2664: 'N::S::S(const N::S %)': cannot convert argument 1 from
'Platform::String ^' to 'const N::S %'
This works greatly with the standard c++ like this:
struct T
{
wstring x;
};
T x { L"test" };
I do not want to use a constructor here.
I assume you mean you don't want a public constructor on the projected WinRT type -- no problem, you can use the internal keyword to mean "public inside C++ but not exposed through interop". That means you can even use native C++ types for your parameters if you like:
namespace Testing
{
public ref class MyTest sealed
{
public:
property String^ Foo {
String^ get() { return m_foo; }
void set(String^ value) { m_foo = value; }
}
internal:
// Would not compile if it was public, since wchar_t* isn't valid
MyTest(const wchar_t* value) { m_foo = ref new String(value); }
private:
String^ m_foo;
};
}
MainPage::MainPage()
{
// Projected type does NOT have this constructor
Testing::MyTest t{ L"Hello" };
OutputDebugString(t.Foo->Data());
t.Foo = "\nChanged";
OutputDebugString(t.Foo->Data());
}
Also you don't need to have the private variable to hold the string -- you could just use the auto-property as in your original code -- but I prefer to be explicit. It also means that if you needed to access the string a lot from within your C++ code you could provide an internal accessor function and not have to go through a vtable call to get at it.

Static call method in Dart Classes (make Classes callable)

For an embedded DSL I want classes to behave like a function. It seems easy for instances (https://www.dartlang.org/articles/emulating-functions/) but I couldn't make it happen for classes. I tried creating a static call a method but this didn't work either.
Is there a way or do I have to give the class another name and make Pconst a function, calling the constructor?
class Pconst {
final value;
Pconst(this.value);
static Pconst call(value) => new Pconst(value);
String toString() => "Pconst($value)";
}
void main() {
var test = Pconst(10);
// Breaking on exception: Class '_Type' has no instance method 'call'.
print("Hello, $test");
}
class TestA {
call(int a, int b) => a + b;
}
void main()
var TA = new TestA();
int integer = TA(3, 4);
print (integer);
}
The call() method is special, in that anyone who defines a call() method is presumed to dynamically emulate a function. This allows us to use instances of TestA as if they were functions that take two integer arguments.
I'd try something like this:
class _PConst{
final value;
_Pconst(this.value);
String toString() => "Pconst($value)";
}
PConst(value){
return new _PConst(value);
}
void main() {
var test = Pconst(10);
print("Hello, $test"); //should work ok
}
so your basically just hiding/wrapping your classes constructor behind a bog standard function.

Passing C++/CLI Class Method as C function pointer

I have a third-party C library that provides this header:
//CLibrary.h
#include <Windows.h>
#include <process.h>
typedef void (WINAPI *CLibEventCallback)(int event, void *data);
__declspec(dllexport) bool CLibStart (CLibEventCallback callback, void *data);
// CLibrary.c -- sample implementation
static CLibEventCallback cb;
void _cdecl DoWork (void *ptr)
{
for (int i = 0; i < 10; ++i)
{
cb (i*i, ptr);
Sleep (500);
}
}
__declspec(dllexport) bool CLibStart (CLibEventCallback callback, void *data)
{
cb = callback; // save address for DoWork thread...
_beginthread (DoWork, 0, data);
return true;
}
I need to create a C++/CLI class that can call CLibStart and provide a class method as the function pointer. As suggested below, this needs to be done with GetFunctionPointerForDelegate. Because the delete constructor includes 'this' and doesn't require a static method, I don't need to pass 'this' into CLibStart.
using namespace System;
using namespace System::Runtime::InteropServices;
namespace Sample {
public ref class ManagedClass
{
delegate void CLibraryDelegate (int event, void *data);
private:
CLibraryDelegate^ managedDelegate;
IntPtr unmanagedDelegatePtr;
int someInstanceData;
public:
ManagedClass()
{
this->managedDelegate = gcnew CLibraryDelegate(this, &ManagedClass::ManagedCallback);
this->unmanagedDelegatePtr = Marshal::GetFunctionPointerForDelegate(this->managedDelegate);
this->someInstanceData = 42;
}
void Start ()
{
// since the delegate includes an implicit 'this' (as static function is not needed)
// I no longer need to pass 'this' in the second parameter!
CLibStart ((CLibEventCallback) (void *) unmanagedDelegatePtr, nullptr);
}
private:
void Log (String^ msg)
{
Console::WriteLine (String::Format ("someInstanceData: {0}, message: {1}", this->someInstanceData, msg));
}
void ManagedCallback (int eventType, void *data)
{
// no longer need "data" to contain 'this'
this->Log (String::Format ("Received Event {0}", eventType));
}
};
}
All of this compiles and runs fine using this C# tester:
using System;
using Sample;
namespace Tester
{
class Program
{
static void Main(string[] args)
{
var mc = new ManagedClass();
mc.Start();
Console.ReadKey();
}
}
}
Sample output:
Received Event 0
Received Event 1
Received Event 4
Received Event 9
Received Event 16
Received Event 25
Received Event 36
Received Event 49
Received Event 64
Received Event 81
Outstanding questions:
I have this feeling that I need to use gcroot and/or pin_ptr? If
so, how? where?
Thanks.
gcroot should be in place where ref class stores delegate, like:
gcroot<CLibraryDelegate^> managedDelegate;

Getting a return value or exception from AspectJ?

I am able to get the signature and arguments from advised method calls, but I cannot figure out how to get the return values or exceptions. I'm kind of assuming that it can be done in some way using around and proceed.
You can use after() returning and after() throwing advices as in beginning of the following document. If you're using #AspectJ syntax please refer to #AfterReturning and #AfterThrowing annotations (you can find samples here).
You can also get return value using after returing advice.
package com.eos.poc.test;
public class AOPDemo {
public static void main(String[] args) {
AOPDemo demo = new AOPDemo();
String result= demo.append("Eclipse", " aspectJ");
}
public String append(String s1, String s2) {
System.out.println("Executing append method..");
return s1 + s2;
}
}
The defined aspect for getting return value:
public aspect DemoAspect {
pointcut callDemoAspectPointCut():
call(* com.eos.poc.test.AOPDemo.append(*,*));
after() returning(Object r) :callDemoAspectPointCut(){
System.out.println("Return value: "+r.toString()); // getting return value
}
Using an around() advice, you can get the return value of the intercepted method call by using proceed(). You can even change the value returned by the method if you want to.
For instance, suppose you have a method m() inside class MyClass:
public class MyClass {
int m() {
return 2;
}
}
Suppose you have the following aspect in its own .aj file:
public aspect mAspect {
pointcut mexec() : execution(* m(..));
int around() : mexec() {
// use proceed() to do the computation of the original method
int original_return_value = proceed();
// change the return value of m()
return original_return_value * 100;
}
}