How do I call a Win32 DLL void** parameter using Win32::API? - windows

I have a Windows DLL that I want to call from Perl. The prototype for the exported function is:
int __stdcall func(const char*, int, int, int, double, double, void**);
The last parameter returns a pointer to an object that is allocated in the function.
The perl code –
my $dll_path = "../stage/test_dll.dll";
my $dll_func = new Win32::API($dll_path,
'func',
'PIIIDDP', 'I');
my $data = "test something here";
my $pResult = 0;
my $rc = $ dll_func ->Call($data, 0, 0, 9, 0.6, 0.3, $pResult);
An error message popped up saying that the memory can’t be written. Maybe I can’t use P to represent void**? I read through all the documentation and could not locate a single example that uses void** parameter. Help!

The variable associated with a P parameter must be a pre-allocated string variable, not an integer. Try something like:
my $pResult = "\0" x 8; # Just in case we're 64-bit
my $rc = $ dll_func ->Call($data, 0, 0, 9, 0.6, 0.3, $pResult);
$pResult will then contain the pointer to the object. You'll probably need to use unpack to extract it.
You don't say what you need to do with the object. If you need to pass it to other DLL functions as a void*, you'll probably need to unpack it as a long and use N instead of P in the parameter list.

Take a look at how swig would do it. Maybe you will find your answer there.

This answer might be off base, but the Inline::C module offers a pretty good interface into user libraries, and within Perl and C you can come up with all kinds of workarounds to passing data through a void** pointer.
use Inline C => DATA => LIBS => '-L../stage -ltest_dll';
my $data = "test something here";
my $rc = func_wrapper($data, 0, 0, 9, 0.6, 0.3);
my $p = get_pointer();
printf "func() set a pointer value of 0x%x\n", $p;
__END__
__C__
#include <stdio.h>
int func(const char *, int, int, int, double, double, void **);
void* pointer_value;
long get_pointer()
{
return (long) pointer_value;
}
/*
* Wraps func() in test_dll library.
*/
int func_wrapper(const char *s, int i1, int i2, int i3, double d1, double d2)
{
void *p = (void *) "some pointer";
int rval = func(s, i1, i2, i3, d1, d2, &p);
/* func() may have changed p as a side effect */
/* for demonstation, save it to a long value that can be retrieved with
the get_pointer() function. There are other ways to pass the pointer
data into Perl. */
pointer_value = p;
printf("The pointer value from func() is %p\n", p);
return rval;
}
If Inline::C looks interesting to you, the Inline::C-Cookbook page on CPAN is also indispensable.

Related

Pass v.cwiseAbs() to a function that accept Ref<VectorXd>

The following does not seem to work.
void Foo(Ref<VectorXd> v) {
// modifies v
}
Eigen::VectorXd v;
Foo(v.cwiseAbs());
With the following error message
error: could not convert 'Eigen::ArrayBase::cwiseAbs() const with Derived = Eigen::ArrayWrapper, -1, 1, true>, -1, 1, false> >; Eigen::ArrayBase::CwiseAbsReturnType = Eigen::CwiseUnaryOp, const Eigen::ArrayWrapper, -1, 1, true>, -1, 1, false> > >; typename Eigen::internal::traits::Scalar = double' from 'const CwiseAbsReturnType {aka const Eigen::CwiseUnaryOp, const Eigen::ArrayWrapper, -1, 1, true>, -1, 1, false> > >}' to 'Eigen::Ref >'
Any suggestions why and how to fix?
This doesn't work, because two additional const qualifiers are required in order to mach the expression returned by .cwiseAbs(). This makes sense, because it should not be possible to modify the result of v.cwiseAbs() by a function that accepts this argument in the form of a reference. The following code compiles:
void Foo(const Ref<const VectorXd>& v) {
std::cout << v << std::endl;
}
int main() {
Eigen::VectorXd v(3);
v << 1,-2,3;
Foo(v.cwiseAbs());
}
With this modification, however, it is not allowed to modify v within Foo().
The simplest solution is probably to drop Ref<> and to use
Foo(VectorXd v) {...}
instead. This generates a local copy, but this should not be an issue in terms of performance, moreover since it is anyhow impossible to avoid any copy if v is to be modified within Foo(). If Ref is kept in the signature of Foo, one can make a copy of v.cwiseAbs() and call Foo() with that copy:
void Foo(Ref<VectorXd> v) {...}
...
Eigen::VectorXd w = v.cwiseAbs();
Foo(w);
As suggested by #chtz, an alternative that is available with C++11 is
void Foo(VectorXd&& v) {...}
While this allows to modify v within Foo(), it can be somewhat dangerous to use because only a temporary is changed in Foo(). Modifications of v done in Foo() will not change v in main().

How to return multiple values (vector and one int value) through function

I am finding connected components of a graph.
Condition : Those components should not be printed in same function, but they should be printed in calling function ( i.e. int main() )
I have gone through the link but got some error.
Returning multiple values from a C++ function
tuple <vector<int>&, int > connected( vector<int>& store, ...)
{
int component_size = 0;
// code
return make_tuple ( store, component_size);
}
int main()
{
// code
for( int i = 0 ; i < V; i++ )
{
if( !visited[i])
{
tie( ans, compo_size ) = connected(edges,
visited, myQ, store, V, i);
for(int i = 0 ; i < compo_size; i++ )
{
cout<< ans[i] <<" ";
}
}
}
}
There are few errors :
error: could not convert 'std::make_tuple(_Elements&& ...) [with _Elements = {std::vector >&, int&}](component_size)' from 'std::tuple >, int>' to 'std::tuple >&, int>'
return make_tuple ( store, component_size);
^
error: invalid initialization of reference of type 'std::vector&' from expression of type 'std::vector'
tie( ans, compo_size ) = connected(edges, visited, myQ, store, V, i);
How to return multiple values (vector and one int value) through function
A function can have at most one return value.
Returning more objects can be emulated by either
modifying one or more objects that are global or are referenced by arguments through indirection or by
returning an object of class type that has multiple sub objects.
You've attempted the latter approach through the use of tuple class template. The reason it doesn't work is explained in the documentation:
template< class... Types >
tuple<VTypes...> make_tuple( Types&&... args );
For each Ti in Types..., the corresponding type Vi in VTypes... is std::decay<Ti>::type unless application of std::decay results in std::reference_wrapper<X> for some type X, in which case the deduced type is X&.
As such, your invocation of make_tuple is deduced to return tuple <vector<int>, int > which is wrong because the function is supposed to return tuple <vector<int>&, int > instead. This can be fixed using std::ref so that the correct type is deduced:
std::make_tuple(std::ref(store), component_size);
As eerorika mentioned, you could use std::ref() as follow:
std::tuple <std::vector<int>&, int > connected( std::vector<int>& store, ...)
{
int component_size = 0;
// code
return std::make_tuple ( std::ref(store), component_size);
}
However, there is really no point in returning a reference to the input vector since it is already a non-const reference on input. So changing the vector in place is going to be enough. On return you get a modified version. However, that's probably not what you are looking to do (i.e. you probably wanted to make a copy of store and return the copy with the other arrays appended...)
That also means you're going to have yet another copy when you create the tuple:
std::tuple <std::vector<int>, int > connected( std::vector<int>& store, ...)
{
int component_size = 0;
std::vector<int> result;
// or maybe a straight copy, depends on your needs in "code"
//std::vector<int> result(store);
// code
return std::make_tuple ( result, component_size);
}
As mentioned by others, having a result in the list of arguments is probably your best bet:
int connected( std::vector<int> & result, std::vector<int> const & store, ...)
{
int component_size = 0;
// code
return component_size;
}
Also, wouldn't component_size == result.size() be true? If so, you should not return anything because it's going to be more confusing.
That simplifies the function to this point:
void connected( std::vector<int> & result, std::vector<int> const & store, ...)
{
// code
}

Cannot understand how jCuda cuLaunchKernel work?

I am trying to understand how to use Cuda in Java. I am using jCuda.
Everything was fine until I came across an example containing the code:
// Set up the kernel parameters: A pointer to an array
// of pointers which point to the actual values.
Pointer kernelParameters = Pointer.to(
Pointer.to(new int[]{numElements}),
Pointer.to(deviceInputA),
Pointer.to(deviceInputB),
Pointer.to(deviceOutput)
);
The kernel function prototype is:
__global__ void add(int n, float *a, float *b, float *sum)
The question is:
In terms of c, does it not seem that we are passing something like?
(***n, ***a, ***b, ***sum)
So basically, do we always have to have:
Pointer kernelParameters = Pointer.to( double pointer, double pointer, ...)???
Thank you
The cuLaunchKernel function of JCuda corresponds to the cuLaunchKernel function of CUDA. The signature of this function in CUDA is
CUresult cuLaunchKernel(
CUfunction f,
unsigned int gridDimX,
unsigned int gridDimY,
unsigned int gridDimZ,
unsigned int blockDimX,
unsigned int blockDimY,
unsigned int blockDimZ,
unsigned int sharedMemBytes,
CUstream hStream,
void** kernelParams,
void** extra)
where the kernelParams is the only parameter that is relevant for this question. The documentation says
Kernel parameters can be specified via kernelParams. If f has N parameters, then kernelParams needs to be an array of N pointers. Each of kernelParams[0] through kernelParams[N-1] must point to a region of memory from which the actual kernel parameter will be copied.
The key point here is the last sentence: The elements of the kernelParams array are not the actual kernel parameters. They only point to the actual kernel parameters.
And indeed, this has the odd effect that for a kernel that receives a single float *pointer, you could basically set up the kernel parameters as follows:
float *pointer= allocateSomeDeviceMemory();
float** pointerToPointer = &pointer;
float*** pointerToPointerToPointer = &pointerToPointer;
void **kernelParams = pointerToPointerToPointer;
(This is just to make clear that this is indeed a pointer to a pointer to a pointer - in reality, wou wouldn't write it like that)
Now, the "structure" of the kernel parameters is basically the same for JCuda and for CUDA. Of course you can not take "the address of a pointer" in Java, but the number of indirections is the same. Imagine you have a kernel like this:
__global__ void example(int value, float *pointer)
In the CUDA C API, you can then define the kernel parameters as follows:
int value = 123;
float *pointer= allocateSomeDeviceMemory();
int* pointerToValue = &value;
float** pointerToPointer = &pointer;
void **kernelParams = {
pointerToValue,
pointerToPointer
};
The setup is done analogously in the JCuda Java API:
int value = 123;
Pointer pointer= allocateSomeDeviceMemory();
Pointer pointerToValue = Pointer.to(new int[]{value});
float** pointerToPointer = Pointer.to(pointer);
Pointer kernelParameters = Pointer.to(
pointerToValue,
pointerToPointer
);
The main difference that is relevant here is that you can write this a bit more concisely in C, using the address operator &:
void **kernelParams = {
&value, // This can be imagined as a pointer to an int
&pointer // This can be imagined as a pointer to a pointer
};
But this is basically the same as in the example that you provided:
Pointer kernelParameters = Pointer.to(
Pointer.to(new int[]{value}), // A pointer to an int
Pointer.to(pointer) // A pointer to a pointer
);
Again, the key point is that with something like
void **kernelParams = {
&value,
};
or
Pointer kernelParameters = Pointer.to(
Pointer.to(new int[]{value}),
);
you are not passing the value to the kernel directly. Instead, you are telling CUDA: "Here is an array of pointers. The first pointer points to an int value. Copy the value from this memory location, and use it as the actual value for the kernel call".

How to send a variable of type struct in MPI_Send()?

I have coded a program in C using MPI wherein the struct variable is to be sent in a ring fashion to the processes and, based on the value received from that variable, the work for that particular process is assigned.
The problem is I need to know how to to send a struct variable in the MPI_Send() function as it is giving INVALID DATATYPE at the runtime , Consider the following example
struct info{
int ne, n, u, v, process, min, strip, mincost, b;
} stat;
MPI_Send(&stat,sizeof(stat),sizeof(struct info),1,2,MPI_COMM_WORLD);
You have to do some operation before send a struct.
I wrote the code for your example but to understand better you should read some documentation.
Anyway, here some tips:
If you have a struct made of just one kind of elements, like in your example that all the vars are int, it's better to send a vector taking care the position of each variable.
If you had other kinds, you have to set count to 2 or more and change all the other arrays (e.g: array_of_types, array_of_blocklengths et cetera).
You can calculate the values of array_of_displaysments on your own in that case take care of the Data structure alignment.
If for example you have the struct that follows, x will start from 0 but y from 8, because a padding of 4 bytes will be add to align the elements. struct point{ int x; double y; };
If you don't want to calculate the array_of_displaysments always use MPI_Get_Address and do not rely on the & operator.
Here the code:
struct info{
int ne, n, u, v, process,min,strip,mincost,b;
}stat;
int main(...){
/*MPI INIT*/
struct info _info,
int count; //Says how many kinds of data your structure has
count = 1; //1, 'cause you just have int
// Says the type of every block
MPI_Datatype array_of_types[count];
// You just have int
array_of_types[0] = MPI_INT;
// Says how many elements for block
int array_of_blocklengths[count];
// You have 8 int
array_of_blocklengths[0] = {8};
/* Says where every block starts in memory, counting from the beginning of the struct. */
MPI_Aint array_of_displaysments[coun];
MPI_Aint address1, address2;
MPI_Get_address(&_info,&address1);
MPI_Get_address(&_info.ne,&address2);
array_of_displaysments[0] = address2 - address1;
/*Create MPI Datatype and commit*/
MPI_Datatype stat_type;
MPI_Type_create_struct(count, array_of_blocklengths, array_of_displaysments, array_of_types, &stat_type);
MPI_Type_commit(&stat_type);
// Now we are ready to send
MPI_Send(&_info, 1, stat_type, dest, tag, comm),
/* . . . */
// Free datatype
MPI_Type_free(&stat_type);
// MPI finalization
MPI_Finalize();
}
try this
MPI_Send(&stat,sizeof(struct info),MPI_CHAR,1,2,MPI_COMM_WORLD);
MPI_Recv(&data,sizeof(struct info), MPI_CHAR, 0, DEFAULT_TAG, MPI_COMM_WORLD, &status);
stat = (struct info *) data;

cant find error in printf function

following is code of function
void printf(char *ch,void *num,...)
{
int i;
va_list ptr; //to store variable length argument list
va_start(ptr,num); // initialise ptr
for(i=0;ch[i]!='\0';i++)
{
if(ch[i]=='%') // check for % sign in print statement
{ i++;
if( ch[i]=='d')
{
int *no = (int *)va_arg(ptr,int * );
int value=*no; // just used for nothing
printno(value); //print int number
}
if( ch[i]=='u')
{
unsigned long *no =(unsigned long *) va_arg(ptr,unsigned long *);
unsigned long value=*no;
printuno(value); //print unsigned long
}
}
else // if not % sign then its regular character so print it
{
printchar(ch[i]);
}
}
}
this my code for printf() to print integer value and uint values
It is working fine for string portion in arguments but for %d %u it shows the same
values for all variables. This value is 405067 - even though the values of the variables are different.
Please tell me how to fix this.
Why are you interpreting the argument as a pointer? I'm surprised you aren't crashing. You should just be using
int num = va_arg(ptr,int);
printno(num);
and
unsigned int num = va_arg(ptr,unsigned int);
printuno(value);
(note, unsigned int, not unsigned long, because that would actually be %lu)
Also, get rid of the num parameter. It's wrong. Your va_list should be initialized as
`va_start(ptr, ch);`
va_start() takes the last argument before the varargs, not the first argument.
As noted in a comment, the C99 prototype for printf() is:
int printf(const char * restrict format, ...);
Therefore, if you're calling your function printf(), you should probably follow its design. I'm going to ignore flags, field width, precision and length modifiers, assuming that the conversion specifiers are simply two characters each, such as %d or %%.
int printf(const char * restrict format, ...)
{
va_list args;
va_start(args, format);
char c;
int len = 0;
while ((c = *format++) != '\0')
{
if (c != '%')
{
putchar(c);
len++;
}
else if ((c = *format++) == '%')
{
putchar(c);
len++;
}
else if (c == 'd')
{
int value = va_arg(args, int);
len += printno(value);
}
else if (c == 'u')
{
unsigned value = va_arg(args, unsigned);
len += printuno(value);
}
else
{
/* Print unrecognized formats verbatim */
putchar('%');
putchar(c);
len += 2;
}
}
return len;
}
Dealing with the full set of format specifiers (especially if you add the POSIX n$ notation as well as flags, field width, precision and length modifiers) is much harder, but this should get you moving in the correct direction. Note that I assume the printno() and printuno() functions both report how many characters were written for the conversion specifier. The function returns the total number of characters written. Note, too, that production code would need to allow for the called functions to fail, and would therefore probably not use the len += printno(value); notation, but would capture the return from printno() into a separate variable that could be tested for an error before adding it to the total length output.

Resources