Vala: number of cpus - glib

I am trying to get my machine's number of cpus in vala.
According to http://valadoc.org/#!wiki=glib-2.0/index
public uint get_num_processors ()
should return this to me.
But when I try to compile the following code:
public class Main {
static int main(string[] args) {
uint num_cpus = GLib.get_num_processors();
return 0;
}
}
with:
valac --target-glib 2.38 --pkg gtk+-3.0 --pkg gee-1.0 $(SRC)
I see the following error:
Application.vala:28.4-28.26: error: The name 'get_num_processors' does
not exist in the context of 'GLib'
I've tested some other methods from GLib. They all work flawless except this one.
Has anyone an idea what I'm doing wrong?

The function was only added to the VAPI recently, I believe you'll need version 0.22.0 of Vala (or one of the unstable 0.21.x releases).
To get around this you can create a local binding in your code:
[CCode (cname = "g_get_num_processors")]
private extern static uint get_num_processors ();

This was introduced in GLib 2.36 (see GLib Threads). Do you have that version installed?

Related

Issue compiling with cvstd_wrapper.hpp opencv4.0.1

I was updating earlier c code (opencv1.0) to opencv 4 . While i was changing and updating api's everything looked fine , however, at the end i got the error with the above mentioned file as follows,
/usr/local/include/opencv4/opencv2/core/cvstd_wrapper.hpp:45:40: Declaration of constexpr static data member 'check' requires an initializer
/usr/local/include/opencv4/opencv2/core/cvstd_wrapper.hpp:47:31: Constexpr can only be used in variable and function declarations
I am using LLVM 8.1 and uses libc++(LLVM C++ standard library with c++ 11 support) as c++ standard library.
Following is the part of the code that shows error in opencv.
struct has_parenthesis_operator
{
private:
template<typename T>
CV_CONSTEXPR std::true_type check(typename std::is_same<typename
std::decay<decltype(std::declval<T>().operator()(std::declval<Args> .
()...))>::type, Ret>::type*);
template<typename> static CV_CONSTEXPR std::false_type check(...);
typedef decltype(check<C>(0)) type;
public:
static CV_CONSTEXPR bool value = type::value;
};

Ignore Varargs Warnings In Javac

I want to escalate the missing serialversionUID warning to an error and fail my build when it occurs in javac.
I have added the following to my ant task:
<compilerarg value="-Xlint:serial"/>
<compilerarg value="-Werror"/>
However, the build also fails with varargs warnings:
non-varargs call of varargs method with inexact argument type for last parameter;
cast to java.lang.Object for a varargs call
cast to java.lang.Object[] for a non-varargs call and to suppress this warning
I tried changing the javac task to
<compilerarg value="-Xlint:-varargs"/>
<compilerarg value="-Xlint:serial"/>
<compilerarg value="-Werror"/>
However, it made no difference. How do I make the compiler ignore these warnings and only fail on the serialversionUID?
I am using Ant 1.9.4 and tried with Javac 1.6u37, 1.7u79 and 1.8u92
Example class:
package com.stackoverflow.compiler;
import java.io.Serializable;
public class Main implements Serializable {
public static void foo(Object... args) {
System.out.println("Test foo");
}
public static void main(String[] args) {
// is args supposed to be an array of objects
// or the only element in an array?
foo(args);
}
}
It seems that the warning you have is not related to the -Xlint:varargs option
According to javac reference the varargs option for -Xlint:
Warns about unsafe usages of variable arguments (varargs) methods, in particular, those that contain non-reifiable arguments
The documentation says that the following code:
public class ArrayBuilder {
public static <T> void addToList (List<T> listArg, T... elements) {
for (T x : elements) {
listArg.add(x);
}
}
}
should produce the warning:
warning: [varargs] Possible heap pollution from parameterized vararg type T
The actual warning I get (using javac 1.8.0_65) is:
warning: [unchecked] Possible heap pollution from parameterized vararg type T
(i.e unchecked instead of varargs)
The warning you got can be caused by code like this:
public static void foo(Object... args) {...}
public static void main(String[] args) {
// is args supposed to be an array of objects
// or the only element in an array?
foo(args);
}
That warning went away only using -Xlint:none option, but then -Xlint:serial does nothing. So it seems what you want is not possible.
I know the question is about javac, but let me still mention that ecj can be configured to meet your requirement: simply say -err:serial on the command line.
With that option this source file
public class Serial implements java.io.Serializable {}
will trigger this compiler output
----------
1. ERROR in /tmp/Serial.java (at line 1)
public class Serial implements java.io.Serializable {}
^^^^^^
The serializable class Serial does not declare a static final serialVersionUID field of type long
----------
1 problem (1 error)
Other warnings are not affected by that option. In particular, you could complete suppress the varargs warning by adding -warn:-varargsCast. This isn't necessary because a warning will never let your build fail. But if you really don't want to see this even as a warning, the full command line would look like this:
ecj -err:serial -warn:-varargsCast Main.java
See the JDT FAQ for using ecj in automated builds, incl. ant.

Platform Invoke F# callback functions

I am using F# on a Raspberry Pi 2 (ARM 7 & thus mono). I am currently trying to use the WiringPi library, written in C. I have successfully managed to use some of the functions using P/Invoke.
Now I am trying to use interrupts (see http://wiringpi.com/reference/priority-interrupts-and-threads/) but I am stumped by this function with the following C signature
int wiringPiISR (int pin, int edgeType, void (*function)(void));
Which has been translated (see https://github.com/danriches/WiringPi.Net/blob/master/WiringPi/WrapperClass.cs) by Daniel Riches into a C# library like this
//This is the C# equivelant to "void (*function)(void))" required by wiringPi to define a callback method
public delegate void ISRCallback();
[DllImport("libwiringPi.so", EntryPoint = "wiringPiISR")]
public static extern int wiringPiISR(int pin, int mode, ISRCallback method);
How on earth would I do this in F#? I guess DllImport line looks like this ("method" is reserved in F#)
[<DllImport("libwiringPi.so", EntryPoint = "wiringPiISR")>]
extern int wiringPiISR(int pin, int mode, ISRCallback callBack);
What does the type definition for ISRCallback look like?
Note: this is not just "a" function pointer but a void one, with void arguments.
The delegate definition would look something like this:
type ISRCallback = delegate of unit -> unit
And the platform invoke signature would look like this:
[<DllImport("libwiringPi.so", EntryPoint = "wiringPiISR")>]
extern int wiringPiISR(int pin, int mode, [<MarshalAs(UnmanagedType.FunctionPtr)>]ISRCallback callBack);
An example usage of the function:
let callback : ISRCallback = ISRCallback(fun () -> (*do something interesting here*) ())
let result = wiringPiISR(1, 1, callback)
You should keep in mind that delegates in .NET are subject to garbage collection. It is the responsibility of the developer to ensure that the delegate doesn't "go out of scope" until your native library no longer needs the function callback.

Call libc function from JNA

I use a C library from Java through JNA and one function does not flush properly (since the output appear all at once on program end). I have tried Java side System.out.flush(); with no luck.
In brief, I would like to call C fflush(stdout) from Java. With JNA already there (thus would prefer if no additional library) and without C to write.
I am aware of JNA Library mapping as in this question but that seems overkill to me.
The JNA library wrapping way code is actually not so heavy (at least for the flush all behavior).
protected interface CLibrary extends Library
{
static CLibrary clib = (CLibrary) Native.loadLibrary ("c", CLibrary.class);
int fflush (Pointer stream);
}
/* ... */
CLibrary.clib.fflush (null);
JNA also offer late binding method and these oneliners will do what you want
NativeLibrary.getInstance ("c").getFunction ("fflush").invokeInt (new Object[]{0});
// even shorter
Function.getFunction ("c", "fflush").invokeInt (new Object[]{0});
The tedious part comes when you want to limit flushing to stdout. You have to deal with vendor-specific code (stdout is either defined as a macro expanding to an array, Amtel avr-libc, to a function call, Microsoft msvcrt, or a pointer in GNU libc).
For the libc, you might use (two lines for legibility)
Pointer stdout = NativeLibrary.getInstance ("c").getGlobalVariableAddress ("stdout").getPointer (0);
Function.getFunction ("c", "fflush").invokeInt (new Object[]{stdout});
Adding this answer for Win32 / Win64 users, complementing FabienAndre's for GNU libc.
Selectively flushing the stdout stream calling the system's c library's fflush method via jna is hard and cumbersome. As FabienAndre already mentioned, it is difficult to get a hold of the stdout macro definition. For msvcrt (the Win32 / Win64 C library) it is defined via a function call to __iob_func(); the latter returning a pointer to an array of FILE structures. At index 0 is stdin, index 1 is stdout and index 2 is stderr. So for flushing stdout you even need to know the size of the FILE structure, of course, it is different for Win32 and Win64 ...
The following example is tested under Win64 but ought to work under Win32. It was inspired by the thread JNA solutions to catch stdout/stderr of DLL.
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
public class JnaTest {
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("msvcrt" , CLibrary.class);
Pointer __iob_func();
void printf(String format, Object... args);
int fflush (Pointer stream);
}
public static void main(String[] args) {
int sizeOfFileStructure = Platform.is64Bit() ? 48 : 32;
Pointer stdout = CLibrary.INSTANCE.__iob_func().share(sizeOfFileStructure);
CLibrary.INSTANCE.printf("Hello, World\n");
CLibrary.INSTANCE.fflush(stdout);
}
}

Luabind calling convention issues

I am having an issue with Luabind that I am unsure of how to fix without some over-simplified solution.
Luabind appears to only allow binding to functions using the __cdecl calling convention. In my current project all of the functionality exposed to extensions/plugins is exposed using __stdcall. This leaves me unable to bind the exposed objects directly and instead I have to make wrappers for the objects exposed. This would be fine but there are a lot of objects that would need to be wrapped.
For example, an object can look like this:
struct IObject
{
void __stdcall SomeFunc1( void );
void __stdcall SomeFunc2( const char* );
};
struct IObjectContainer
{
IObject* __stdcall GetObject( int );
IObject* __stdcall GetObject( const char* );
};
struct IObjectCore
{
IObjectContainer* __stdcall GetObjectContainer();
};
I don't have the option of changing the entire projects calling convention currently so I am seeing if someone has a solution to perhaps patch Luabind to work with __stdcall functions. I am not the best with templates and with boost things, so I'm personally unsure where to even start trying to add the ability to use __stdcall functions.
For reference, I am using:
Lua 5.1.4
Luabind 0.9.1
VS2010
Both Lua and Luabind are stock latest versions of their rev. (Not using Lua 5.2 for project restriction reasons, but if there is a __stdcall fix for 5.2/Luabind I will gladly take that as well.)
I could only find a fix for a very old version of Luabind to do this but the patch floating on the net still for that does not line up with the current Luabind code at all.
If there is any other information needed feel free to ask.
Sadly due to inactivity and no further answers from more searching I spoke with the project developer and have gotten the entire project stripped of __stdcall. So the bindings all work fine now via __cdecl. Not the route I wanted to take but things are working as planned now.
I faced the exact same problem when binding OpenGL (with GLEW functions) to Lua, and solved it using variadic templates.
Now if the function is global and you know its address in compile time, you can be good with something like this:
template<typename Signature>
struct wrap_known;
template<typename Ret, typename... Args>
struct wrap_known<Ret __stdcall (Args...)> {
template <Ret __stdcall functor(Args...)>
static Ret invoke(Args... arguments) {
return functor(arguments...);
}
};
// I know using macro is generally a bad idea but it's just shorter
#define wrap(f) wrap_known<decltype(f)>::invoke<f>
and then, when binding, use the macro like this:
luabind::def("Clear", wrap(glClear)),
luabind::def("Vertex4f", wrap(glVertex4f))
However, in your case, we have a bunch of member functions and not globals like above.
Here is the code for wrapping member functions with __stdcall calling convention:
template<typename Signature>
struct wrap_mem;
template<typename Sub, typename Ret, typename... Args>
struct wrap_mem<Ret(__stdcall Sub::*) (Args...)> {
template <Ret(__stdcall Sub::*functor) (Args...)>
static Ret invoke(Sub* subject, Args... arguments) {
return (subject->*functor)(arguments...);
}
};
#define wrap_member(f) wrap_mem<decltype(f)>::invoke<f>
Use it like this:
struct A {
int __stdcall my_method(double b) {
return 2;
}
};
// ...
luabind::class_<A>("A")
.def("my_method", wrap_member(&A::my_method))
Sometimes, however, you are not that lucky to know the function's address in compile time, and this happens with GLEW for example. For functions like glUniform*f, glGetUniformLocation, the "wrap" macro will not work, so I made another version for wrapping functions known at runtime:
template<typename Signature>
struct wrap_unknown;
template<typename Ret, typename... Args>
struct wrap_unknown<Ret (__stdcall*) (Args...)> {
template <Ret (__stdcall** functor)(Args...)>
static Ret invoke(Args... arguments) {
return (**functor)(arguments...);
}
};
#define wrap_ptr(f) wrap_unknown<decltype(f)>::invoke<&f>
(if above code scares you, it is actually a good sign)
Now you can bind GLEW functions like this:
luabind::def("Uniform4f", wrap_ptr(glUniform4f)),
luabind::def("GetUniformLocation", wrap_ptr(glGetUniformLocation))
Just don't ask me to write another version for binding pointers to members known at runtime :)
If you don't want to use C++11 for some reason, here you can find out how to pass function arguments and return value as template parameters in C++03.

Resources