Dart _psapi not found - dart

I am trying to call WinAPI. I have copy-past code from docs:
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';
main() {
int EnumProcesses(
Pointer<Uint32> lpidProcess, int cb, Pointer<Uint32> lpcbNeeded) {
final _EnumProcesses = _psapi.lookupFunction<
Int32 Function(
Pointer<Uint32> lpidProcess, Uint32 cb, Pointer<Uint32> lpcbNeeded),
int Function(Pointer<Uint32> lpidProcess, int cb,
Pointer<Uint32> lpcbNeeded)>('EnumProcesses');
return _EnumProcesses(lpidProcess, cb, lpcbNeeded);
}
}

If you've got a reference to win32, you don't need to copy this code also -- you should already have the EnumProcesses API available to you.
Here's a simple example of how to use it:
import 'dart:ffi';
import 'dart:io';
import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';
int printModules(int processID) {
// Print the process identifier.
print('\nProcess ID: $processID');
// Get a handle to the process.
final hProcess = OpenProcess(
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
if (hProcess == 0) {
return 1;
}
// Get a list of all the modules in this process.
final hMods = allocate<IntPtr>(count: 1024);
final cbNeeded = allocate<Uint32>();
if (EnumProcessModules(
hProcess, hMods, sizeOf<IntPtr>() * 1024, cbNeeded.cast()) ==
1) {
for (var i = 0; i < ((cbNeeded.value / sizeOf<IntPtr>()).floor()); i++) {
final szModName = allocate<Uint16>(count: MAX_PATH).cast<Utf16>();
// Get the full path to the module's file.
final hModule = hMods.elementAt(i).value;
final moduleValue =
'0x${hModule.toRadixString(16).padLeft(sizeOf<IntPtr>(), '0').toUpperCase()}';
if (GetModuleFileNameEx(hProcess, hModule, szModName, MAX_PATH) != 0) {
// Print the module name and handle value.
print('\t${szModName.unpackString(MAX_PATH)} ($moduleValue)');
}
free(szModName);
}
}
free(hMods);
free(cbNeeded);
// Release the handle to the process.
CloseHandle(hProcess);
return 0;
}
void main() {
final aProcesses = allocate<Uint32>(count: 1024);
final cbNeeded = allocate<Uint32>();
// Get the list of process identifiers.
if (EnumProcesses(aProcesses, sizeOf<Uint32>() * 1024, cbNeeded.cast()) ==
0) {
print('EnumProcesses failed.');
exit(1);
}
// Calculate how many process identifiers were returned.
final cProcesses = (cbNeeded.value / sizeOf<Uint32>()).floor();
// Print the names of the modules for each process.
for (var i = 0; i < cProcesses; i++) {
printModules(aProcesses[i]);
}
}

Related

Access Lua coroutine from C

I have implemented a co-routine system. When I press ENTER to clear the first textbox, it calls contscript() which in turn calls lua_resume() but it doesn't continue the co-routine.
So what do I pass to lua_resume() to make the co-routine continue?
static lua_State *lua;
static int luapanic(lua_State *L)
{
allegro_exit();
const char *err = lua_tostring(L, -1);
DEBUGF("lua panic: %s\n", err);
printf("lua panic: %s\n", err);
return 0;
}
static int textbox(lua_State *L)
{
const char *str = luaL_checkstring(L, 1);
message(str);
return 1;
}
void contscript(void)
{
lua_resume(lua,NULL,0);
}
static int transfer_player(lua_State *L)
{
int x, y;
SpriteObj *p;
x = luaL_checkint(L, 1);
y = luaL_checkint(L, 2);
p = findobject(0);
setposition(p,x,y);
scrollToAndCentre(x,y);
return 1;
}
bool initscript(void)
{
lua = luaL_newstate();
lua_atpanic(lua, luapanic);
luaL_openlibs(lua);
lua_register(lua, "textbox", textbox);
lua_register(lua, "transfer_player", transfer_player);
return true;
}
Here is the script in question:
local co = coroutine.wrap(
function()
textbox("Dear me! I never knew birds could sing so\nbeautifully!")
coroutine.yield()
textbox("Text message #2")
end
)
co()

MQL4 How to call OnChartEvent() from init()

I want to call OnChartEvent() from init() like the code below, so the EA should process first the password and then the rest of the code.
I am just newbie not an expert in coding.
The idea or objective, the password must enter first and correctly, after successful then process the rest of code.
#include <ChartObjects/ChartObjectsTxtControls.mqh>
int init()
{
password_edit.Create(0, "password_edit", 0, 10, 10, 260, 25);
password_edit.BackColor(White);
password_edit.BorderColor(Black);
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent( const int id,
const long &lparam,
const double &dparam,
const string &sparam
)
{
//---
if (id == CHARTEVENT_OBJECT_ENDEDIT && sparam == "password_edit" )
{
password_status = -1;
for (int i=0; i<ArraySize(allowed_passwords); i++)
if (password_edit.GetString(OBJPROP_TEXT) == allowed_passwords[i])
{
password_status = i;
break;
}
if (password_status == -1)
{
password_edit.SetString(OBJPROP_TEXT, 0, password_message[0]);
ExpertRemove();
}
else
{
password_edit.SetString(OBJPROP_TEXT, 0, password_message[1]);
}
}
}
//+------------------------------------------------------------------+
int OnInit(){
passwordOperation();
return INIT_SUCCEED;
}
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//---
if (id == CHARTEVENT_OBJECT_ENDEDIT && sparam == "password_edit" )
{
passwordOperation();
}
}
void passwordOperation()
{
password_status = -1;
for (int i=0; i<ArraySize(allowed_passwords); i++)
if (password_edit.GetString(OBJPROP_TEXT) == allowed_passwords[i])
{
password_status = i;
break;
}
if (password_status == -1)
{
password_edit.SetString(OBJPROP_TEXT, 0, password_message[0]);
ExpertRemove();
}
else
{
password_edit.SetString(OBJPROP_TEXT, 0, password_message[1]);
}
}

glib-2.0: g_spawn_command_line_sync() - unknown stdout length

function g_spawn_command_line_sync() has argument "gchar **standard_output":
https://developer.gnome.org/glib/stable/glib-Spawning-Processes.html#g-spawn-command-line-sync
I need read binary data from standard_output, but I not known length of standard_output.
Function g_spawn_command_line_sync():
http://fossies.org/dox/glib-2.38.2/gspawn-win32_8c_source.html#l01452
execute:
GString *outstr = NULL;
*standard_output = g_string_free (outstr, FALSE);
Struct GString include "gsize len", but g_spawn_command_line_sync() accessible only "gchar **".
I have next solution. I write size of stdout to stderr, which not using.
Example code:
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
int main()
{
gint exit_status = 0;
gchar *p_stdout = NULL;
gchar *p_stderr = NULL;
GError *p_error = NULL;
gboolean result;
result = g_spawn_command_line_sync("./make_image.py", &p_stdout, &p_stderr, &exit_status, &p_error);
if (!result) {
if (p_error != NULL) {
printf(p_error->message);
}
else {
printf("ERROR: Command not run\n");
}
}
else if (exit_status != 0) {
printf(p_stderr);
}
else {
int size = atoi(p_stderr);
gchar *p_c = p_stdout;
for (int i = 0; i < size; ++i) {
fputc(*p_c++, stdout);
}
//printf(p_stdout);
}
if (p_stdout) {
g_free(p_stdout);
}
if (p_stderr) {
g_free(p_stderr);
}
if (p_error) {
g_error_free(p_error);
}
return 0;
}
Use g_spawn_async_with_pipes. Reading binary data from file descriptors is easy. If you really need to detect when the child exits, add a callback using g_child_watch_add or g_child_watch_add_full, but you can probably get away with just reading the descriptor until it returns an error.

Why is this Dart code so slow compared to java's implementation?

The dart codes as follows is extremely slow compared to java's implementation.
//test.dart
import 'dart:io';
void main(){
for(int i = 0; i < 1 << 25;i++){
stdout.write(i); // or directly print(i);
}
stdout.close();
}
java version:
//Test.java
import java.io.*;
public class Test{
public static void main(String[]args)throws Exception {
try{
PrintWriter out = new PrintWriter(System.out);
for(int i = 0;i < 1 << 25; i++){
out.print(i);
}
out.close();
}catch(Exception e){}
}
}
$ time java Test > /dev/null
real 0m6.421s
user 0m0.046s
sys 0m0.031s
$ time dart Test.dart > /dev/null
real 0m51.978s
user 0m0.015s
sys 0m0.078s
Is stdout/print() unbuffered by default in Dart? Is there something like java's PrintWriter? thanks. (Update: after warming up vm, stdout is 2x slower than java )
real 0m15.497s
user 0m0.046s
sys 0m0.047s
===============================================================================
Update Sep 30, 2013
I have implemented custom buffers for both dart and java codes to make a further comparing,now the result is as follows:
//test.dart
final int SIZE = 8192;
final int NUM = 1 << 25;
void main(){
List<int> content = new List(SIZE);
content.fillRange(0, SIZE, 0);
for(int i = 0; i < NUM;i++){
if(i % SIZE == 0 && i > 0)
print(content);
content[i % SIZE] = i;
}
if (NUM % SIZE ==0)
print(content);
else
print(content.sublist(0, NUM % SIZE));
}
java version:
//Test.java
import java.util.Arrays;
public class Test{
public static final int SIZE = 8192;
public static final int NUM = 1 << 25;
public static void main(String[]args)throws Exception {
try{
int[] buf = new int[SIZE];
for(int i = 0;i < NUM; i++){
if(i % SIZE == 0 && i > 0)
System.out.print(Arrays.toString(buf));
buf[i % SIZE] = i;
}
if(NUM % SIZE == 0)
System.out.print(Arrays.toString(buf));
else
{
int[] newbuf = new int[NUM % SIZE];
newbuf = Arrays.copyOfRange(buf, 0, (NUM % SIZE));
System.out.print(Arrays.toString(newbuf));
}
}catch(Exception e){}
}
}
$ time java Test > /dev/null
real 0m7.397s
user 0m0.031s
sys 0m0.031s
$ time dart test.dart > /dev/null
real 0m22.406s
user 0m0.015s
sys 0m0.062s
As you see, dart is still 3x slower than java.
Maybe your code does not get optimized by the VM.
Only "frequenly" used functions are compiled and executed as native code.
Usually for such benchmark, you have to put the tested code into a function and perform a warmup. For exemple:
//test.dart
import 'dart:io';
void f(nb_shift) {
for(int i = 0; i < 1 << nb_shift;i++){
stdout.write(i); // or directly print(i);
}
}
void main(){
//warm up:
f(3);
// the test
f(25);
stdout.close();
}
Nicolas

A question of libevent example code: how is invoked?

I'm learning libev however the code is so hard to understand, so I choose to learn libevent first whose code is relatively clearer. But I encounter a problem when try the example (http://www.wangafu.net/~nickm/libevent-book/01_intro.html).
How is the code event_add(state->write_event, NULL) in do_read() make do_write() function invoked?
/* For sockaddr_in */
#include <netinet/in.h>
/* For socket functions */
#include <sys/socket.h>
/* For fcntl */
#include <fcntl.h>
#include <event2/event.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define MAX_LINE 16384
void do_read(evutil_socket_t fd, short events, void *arg);
void do_write(evutil_socket_t fd, short events, void *arg);
char
rot13_char(char c)
{
return c;
/* We don't want to use isalpha here; setting the locale would change
* which characters are considered alphabetical. */
if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M'))
return c + 13;
else if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z'))
return c - 13;
else
return c;
}
struct fd_state {
char buffer[MAX_LINE];
size_t buffer_used;
size_t n_written;
size_t write_upto;
struct event *read_event;
struct event *write_event;
};
struct fd_state *
alloc_fd_state(struct event_base *base, evutil_socket_t fd)
{
struct fd_state *state = malloc(sizeof(struct fd_state));
if (!state)
return NULL;
state->read_event = event_new(base, fd, EV_READ|EV_PERSIST, do_read, state);
if (!state->read_event) {
free(state);
return NULL;
}
state->write_event =
event_new(base, fd, EV_WRITE|EV_PERSIST, do_write, state);
if (!state->write_event) {
event_free(state->read_event);
free(state);
return NULL;
}
state->buffer_used = state->n_written = state->write_upto = 0;
assert(state->write_event);
return state;
}
void
free_fd_state(struct fd_state *state)
{
event_free(state->read_event);
event_free(state->write_event);
free(state);
}
void
do_read(evutil_socket_t fd, short events, void *arg)
{
struct fd_state *state = arg;
char buf[1024];
int i;
ssize_t result;
while (1) {
assert(state->write_event);
result = recv(fd, buf, sizeof(buf), 0);
if (result <= 0)
break;
for (i=0; i < result; ++i) {
if (state->buffer_used < sizeof(state->buffer))
state->buffer[state->buffer_used++] = rot13_char(buf[i]);
if (buf[i] == '\n') {
assert(state->write_event);
**event_add(state->write_event, NULL);**
state->write_upto = state->buffer_used;
}
}
}
if (result == 0) {
free_fd_state(state);
} else if (result < 0) {
if (errno == EAGAIN) // XXXX use evutil macro
return;
perror("recv");
free_fd_state(state);
}
}
void
**do_write(evutil_socket_t fd, short events, void *arg)**
{
struct fd_state *state = arg;
while (state->n_written < state->write_upto) {
ssize_t result = send(fd, state->buffer + state->n_written,
state->write_upto - state->n_written, 0);
if (result < 0) {
if (errno == EAGAIN) // XXX use evutil macro
return;
free_fd_state(state);
return;
}
assert(result != 0);
state->n_written += result;
}
if (state->n_written == state->buffer_used)
state->n_written = state->write_upto = state->buffer_used = 1;
event_del(state->write_event);
}
void
do_accept(evutil_socket_t listener, short event, void *arg)
{
struct event_base *base = arg;
struct sockaddr_storage ss;
socklen_t slen = sizeof(ss);
int fd = accept(listener, (struct sockaddr*)&ss, &slen);
if (fd < 0) { // XXXX eagain??
perror("accept");
} else if (fd > FD_SETSIZE) {
close(fd); // XXX replace all closes with EVUTIL_CLOSESOCKET */
} else {
struct fd_state *state;
evutil_make_socket_nonblocking(fd);
state = alloc_fd_state(base, fd);
assert(state); /*XXX err*/
assert(state->write_event);
event_add(state->read_event, NULL);
}
}
void
run(void)
{
evutil_socket_t listener;
struct sockaddr_in sin;
struct event_base *base;
struct event *listener_event;
base = event_base_new();
if (!base)
return; /*XXXerr*/
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0;
sin.sin_port = htons(40713);
listener = socket(AF_INET, SOCK_STREAM, 0);
evutil_make_socket_nonblocking(listener);
#ifndef WIN32
{
int one = 1;
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
}
#endif
if (bind(listener, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
perror("bind");
return;
}
if (listen(listener, 16)<0) {
perror("listen");
return;
}
listener_event = event_new(base, listener, EV_READ|EV_PERSIST, do_accept, (void*)base);
/*XXX check it */
event_add(listener_event, NULL);
event_base_dispatch(base);
}
int
main(int c, char **v)
{
setvbuf(stdout, NULL, _IONBF, 0);
run();
return 0;
}
I'm not sure if I'm answering the same question you asked - I understand it as:
How does calling event_add(state->write_event, NULL) in do_read() lead to do_write() being invoked?
The key to figuring this out is understanding what the do_read() function is actually doing. do_read() is a callback function associated with a socket which has data to be read: this is set up with allocate_fd_state():
struct fd_state *
alloc_fd_state(struct event_base *base, evutil_socket_t fd)
{
/*
* Allocate a new fd_state structure, which will hold our read and write events
* /
struct fd_state *state = malloc(sizeof(struct fd_state));
[...]
/*
* Initialize a read event on the given file descriptor: associate the event with
* the given base, and set up the do_read callback to be invoked whenever
* data is available to be read on the file descriptor.
* /
state->read_event = event_new(base, fd, EV_READ|EV_PERSIST, do_read, state);
[...]
/*
* Set up another event on the same file descriptor and base, which invoked the
* do_write callback anytime the file descriptor is ready to be written to.
*/
state->write_event =
event_new(base, fd, EV_WRITE|EV_PERSIST, do_write, state);
[...]
return state;
}
At this point, though, neither of these events have been event_add()'ed to the event_base base. The instructions for what to do are all written out, but no one is looking at them. So how does anything get read? state->read_event is event_add()'ed to the base after an incoming connection is made. Look at do_accept():
void
do_accept(evutil_socket_t listener, short event, void *arg)
{
[ ... accept a new connection and give it a file descriptor fd ... ]
/*
* If the file descriptor is invalid, close it.
*/
if (fd < 0) { // XXXX eagain??
perror("accept");
} else if (fd > FD_SETSIZE) {
close(fd); // XXX replace all closes with EVUTIL_CLOSESOCKET */
/*
* Otherwise, if the connection was successfully accepted...
*/
} else {
[ ... allocate a new fd_state structure, and make the file descriptor non-blocking ...]
/*
* Here's where the magic happens. The read_event created back in alloc_fd_state()
* is finally added to the base associated with it.
*/
event_add(state->read_event, NULL);
}
}
So right after accepting a new connection, the program tells libevent to wait until there's data available on the connection, and then run the do_read() callback. At this point, it's still impossible for do_write() to be called. It needs to be event_add()'ed. This happens in do_read():
void
do_read(evutil_socket_t fd, short events, void *arg)
{
/* Create a temporary buffer to receive some data */
char buf[1024];
while (1) {
[ ... Receive the data, copying it into buf ... ]
[ ... if there is no more data to receive, or there was an error, exit this loop... ]
[ ... else, result = number of bytes received ... ]
for (i=0; i < result; ++i) {
[ ... if there's room in the buffer, copy in the rot13() encoded
version of the received data ... ]
/*
* Boom, headshot. If we've reached the end of the incoming data
* (assumed to be a newline), then ...
*/
if (buf[i] == '\n') {
[...]
/*
* Have libevent start monitoring the write_event, which calls do_write
* as soon as the file descriptor is ready to be written to.
*/
event_add(state->write_event, NULL);
[...]
}
}
}
[...]
}
So, after reading in some data from a file descriptor, the program starts waiting until
the file descriptor is ready to be written to, and then invokes do_write(). Program
flow looks like this:
[ set up an event_base and start waiting for events ]
[ if someone tries to connect ]
[ accept the connection ]
[ ... wait until there is data to read on the connection ... ]
[ read in data from the connection until there is no more left ]
[ ....wait until the connection is ready to be written to ... ]
[ write out our rot13() encoded response ]
I hope that a) that was the correct interpretation of your question, and b) this was a helpful answer.

Resources