I need Windows executables of this project:
https://github.com/ashkang/jcal
I tried adding all .h and a .c files with a main to a single Console non-qt C++ project in Qt Creator but it issues a lot errors like: \jdate\jdate.c:-1 error: undefined reference to jlocaltime_r'.
I have also added unknown files like jasctime_r.3 to the project.
How can I compile this project in Windows?
Ok, it does indeed work, if you use the GNU build system it is intended for, but you do need some code changes to get around missing functions on windows.
localtime_r() and gmtime_r() can be replaced with localtime_s() and gmtime_s() and the arguments swapped.
for strptime(), you need to provide an implementation, here's an open source one that works if you fix the #includes and add a #define TM_YEAR_BASE 1900.
Put the fixed strptime.c in the sources/libjalali directory and apply the following patch:
diff --git a/sources/configure.ac b/sources/configure.ac
index e623ec9..409d9e7 100644
--- a/sources/configure.ac
+++ b/sources/configure.ac
## -66,4 +66,9 ## if test $installpyjalali = "yes"; then
fi
AM_CONDITIONAL([WANT_PYJALALI], [test $installpyjalali = "yes"])
+case $host in
+ *mingw*) targetismingw=yes ;;
+esac
+AM_CONDITIONAL([MINGW], [test x$targetismingw = xyes])
+
AC_OUTPUT
diff --git a/sources/libjalali/Makefile.am b/sources/libjalali/Makefile.am
index 078c68a..64ef85d 100644
--- a/sources/libjalali/Makefile.am
+++ b/sources/libjalali/Makefile.am
## -5,6 +5,9 ##
lib_LTLIBRARIES = libjalali.la
libjalali_la_SOURCES = jalali.c jtime.c
+if MINGW
+libjalali_la_SOURCES += strptime.c
+endif
# 0:0:0
# 0 -> interface version, changes whenever you change the API
diff --git a/sources/libjalali/jalali.c b/sources/libjalali/jalali.c
index 49fc43f..6e3bdd9 100644
--- a/sources/libjalali/jalali.c
+++ b/sources/libjalali/jalali.c
## -28,6 +28,10 ##
#include "jalali.h"
#include "jconfig.h"
+#ifdef _WIN32
+#define localtime_r(timep, result) localtime_s((result), (timep))
+#endif
+
/*
* Assuming *factor* numbers of *lo* make one *hi*, cluster *lo*s and change
* *hi* appropriately. In the end:
## -49,7 +53,9 ## const int jalali_month_len[] = { 31, 31, 31, 31, 31, 31, 30, 30, 30, 30,
const int accumulated_jalali_month_len[] = { 0, 31, 62, 93, 124, 155, 186,
216, 246, 276, 306, 336 };
+#ifndef _WIN32
extern char* tzname[2];
+#endif
/*
* Jalali leap year indication function. The algorithm used here
diff --git a/sources/libjalali/jtime.c b/sources/libjalali/jtime.c
index 319dbdd..ba8ec1a 100644
--- a/sources/libjalali/jtime.c
+++ b/sources/libjalali/jtime.c
## -27,6 +27,11 ##
#include "jalali.h"
#include "jtime.h"
+#ifdef _WIN32
+#define localtime_r(timep, result) localtime_s((result), (timep))
+#define gmtime_r(timep, result) gmtime_s((result), (timep))
+#endif
+
const char* GMT_ZONE = "UTC";
const char* GMT_ZONE_fa = "گرینویچ";
const char* jalali_months[] = { "Farvardin", "Ordibehesht", "Khordaad",
## -65,7 +70,9 ## const char* tzname_fa[2] = { "زمان زمستانی", "زمان تابستان
static char in_buf[MAX_BUF_SIZE] = {0};
static struct jtm in_jtm;
+#ifndef _WIN32
extern char* tzname[2];
+#endif
extern const int jalali_month_len[];
void in_jasctime(const struct jtm* jtm, char* buf)
diff --git a/sources/libjalali/jtime.h b/sources/libjalali/jtime.h
index fd658f1..48b4d9a 100644
--- a/sources/libjalali/jtime.h
+++ b/sources/libjalali/jtime.h
## -56,6 +56,10 ## extern struct jtm* jlocaltime_r(const time_t* timep, struct jtm* result);
extern int jalali_to_farsi(char* buf, size_t n, int padding, char* pad, int d);
+#ifdef _WIN32
+extern char *strptime(const char *buf, const char *fmt, struct tm *tm);
+#endif
+
#ifdef __cplusplus
}
#endif
diff --git a/sources/src/jdate.c b/sources/src/jdate.c
index 8a47e19..cae0329 100644
--- a/sources/src/jdate.c
+++ b/sources/src/jdate.c
## -34,6 +34,11 ##
#include "../libjalali/jtime.h"
#include "jdate.h"
+#ifdef _WIN32
+#define localtime_r(timep, result) localtime_s((result), (timep))
+#define gmtime_r(timep, result) gmtime_s((result), (timep))
+#endif
+
extern char* optarg;
/*
Then, get msys2, start its shell and install packages:
pacman -S mingw32/mingw-w64-i686-gcc msys/autoconf msys/automake msys/libtool
This should be enough I guess.
Now you can use the following commands in the sources directory to build it:
autoreconf -i
./configure
make
Related
I have created with GIMP a C-Source image dump like the following:
/* GIMP RGBA C-Source image dump (example.c) */
static const struct {
guint width;
guint height;
guint bytes_per_pixel; /* 2:RGB16, 3:RGB, 4:RGBA */
guint8 pixel_data[304 * 98 * 2 + 1];
} example= {
304, 98, 2,
"\206\061\206\061..... }
Is there a way to read this in GIMP again in order to get back the original image? because it doesn't seem possible.
Or does it exist a tool that can do this back-conversion?
EDITED
Following some suggestion I tried to write a simple C programme to make the reverse coversion ending up with something very similar to another code found on internet but both dont work:
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "imgs_press.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
using namespace std;
int main(int argc, char** argv) {
int fd;
char *name = "orignal_img.pnm";
fd = open(name, O_WRONLY | O_CREAT, 0644);
if (fd == -1) {
perror("open failed");
exit(1);
}
if (dup2(fd, 1) == -1) {
perror("dup2 failed");
exit(1);
}
// file descriptor 1, i.e. stdout, now points to the file
// "helloworld" which is open for writing
// You can now use printf which writes specifically to stdout
printf("P2\n");
printf("%d %d\n", press_high.width, press_high.height);
for(int x=0; x<press_high.width * press_high.height * 2; x++) {
printf("%d ", press_high.pixel_data[x]);
}
}
As suggested by n-1-8e9-wheres-my-share-m, maybe I need to manipulate the pixels usign the correct decode, but I have no idea how to do that, does anybody have other suggestions?
The image I got is indeed distorted:
Updated Answer
If you want to decode the RGB565 and write a NetPBM format PNM file without using ImageMagick, you can do this:
#include <stdint.h> /* for uint8_t */
#include <stdio.h> /* for printf */
/* tell compiler what those GIMP types are */
typedef int guint;
typedef uint8_t guint8;
#include <YOURGIMPIMAGE>
int main(){
int w = gimp_image.width;
int h = gimp_image.height;
int i;
uint16_t* RGB565p = (uint16_t*)&(gimp_image.pixel_data);
/* Print P3 PNM header on stdout */
printf("P3\n%d %d\n255\n",w, h);
/* Print RGB pixels, ASCII, one RGB pixel per line */
for(i=0;i<w*h;i++){
uint16_t RGB565 = *RGB565p++;
uint8_t r = (RGB565 & 0xf800) >> 8;
uint8_t g = (RGB565 & 0x07e0) >> 3;
uint8_t b = (RGB565 & 0x001f) << 3;
printf("%d %d %d\n", r, g ,b);
}
}
Compile with:
clang example.c
And run with:
./a.out > result.pnm
I have not tested it too extensively beyond your sample image, so you may want to make a test image with some reds, greens, blues and shades of grey to ensure that all my bit-twiddling is correct.
Original Answer
The easiest way to get your image back would be... to let ImageMagick do it.
So, take your C file and add a main() to it that simply writes the 304x98x2 bytes starting at &(example.pixel_data) to stdout:
Compile it with something like:
clang example.c -o program # or with GCC
gcc example.c -o program
Then run it, writing to a file for ImageMagick with:
./program > image.bin
And tell ImageMagick its size, type and where it is and what you want as a result:
magick -size 304x98 RGB565:image.bin result.png
I did a quick, not-too-thorough test of the following code and it worked fine for an image I generated with GIMP. Note it doesn't handle alpha/transparency but that could be added if necessary. Save it as program.c:
#include <unistd.h> /* for write() */
#include <stdint.h> /* for uint8_t */
/* tell compiler what those GIMP types are */
typedef int guint;
typedef uint8_t guint8;
<PASTE YOUR GIMP FILE HERE>
int main(){
/* Work out how many bytes to write */
int nbytes = example.width * example.height * 2;
/* Write on stdout for redirection to a file - may need to reopen in binary mode if on Windows */
write(1, &(example.pixel_data), nbytes);
}
If I run this with the file you provided via Google Drive I get:
Dear fellow programmers,
Currently I am working on implementing a Microsoft RPC server / client program on Windows. Using nmake, I managed to compile the client-side of the program, but the server-side gives some problems.
The following relevant files are:
Example1.idl
[
uuid(30f190d8-b966-4619-8f45-72342e6ad058),
version(1.0)
]
interface Example1
{
void Output(
[in, string] const char* szOutput
);
}
Example1.acf
[
implicit_handle(handle_t hExample1Binding)
]
interface Example1
{
}
Example1Server.cpp
#include <iostream>
#include "Example1.h"
void Output(
/* [string][in] */ const char* szOutput)
{
std::cout << szOutput << '\n';
}
RPC_STATUS CALLBACK SecurityCallback(RPC_IF_HANDLE, void*)
{
return RPC_S_OK;
}
int main()
{
RPC_STATUS status;
status = RpcServerUseProtseqEp(
reinterpret_cast<unsigned char*>("ncacn_ip_tcp"),
RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
reinterpret_cast<unsigned char*>("4747"),
NULL);
if (status) exit(status);
status = RpcServerRegisterIf2(
Example1_v1_0_s_ifspec,
NULL,
NULL,
RPC_IF_ALLOW_CALLBACKS_WITH_NO_AUTH,
RPC_C_LISTEN_MAX_CALLS_DEFAULT,
(unsigned)-1,
SecurityCallback);
if (status) exit(status);
status = RpcServerListen(
1,
RPC_C_LISTEN_MAX_CALLS_DEFAULT,
FALSE);
if (status) exit(status);
}
void* __RPC_USER midl_user_allocate(size_t size)
{
return malloc(size);
}
void __RPC_USER midl_user_free(void* p)
{
free(p);
}
makefile
!include <Win32.mak>
# all : Example1Client Example1Server
all : Example1Server
# # Make the client side application Example1Client. This works without compilation problems.
# Example1Client : Example1Client.exe
# Example1Client.exe : Example1Client.obj Example1_c.obj
# $(link) $(linkdebug) $(conflags) -out:Example1Client.exe \
# Example1Client.obj Example1_c.obj \
# rpcrt4.lib $(conlibs)
# # Example1Client main program
# Example1Client.obj : Example1Client.cpp Example1.h
# $(cc) $(cdebug) $(cflags) $(cvars) $*.cpp
# # Example1Client stub
# Example1_c.obj : Example1_c.c Example1.h
# $(cc) $(cdebug) $(cflags) $(cvars) $*.c
# Make the server side application Example1Server
Example1Server : Example1Server.exe
Example1Server.exe : Example1Server.obj Example1_s.obj
$(link) $(linkdebug) $(conflags) -out:Example1Server.exe \
Example1Server.obj Example1_s.obj \
rpcrt4.lib $(conlibsmt)
# Example1Server main program
Example1Server.obj : Example1Server.cpp Example1.h
$(cc) $(cdebug) $(cflags) $(cvarsmt) $*.cpp
# Example1Server stub file
Example1_s.obj : Example1_s.c Example1.h
$(cc) $(cdebug) $(cflags) $(cvarsmt) $*.c
# Stubs and header file from the IDL file
Example1.h Example1_c.c Example1_s.c : Example1.idl Example1.acf
midl Example1.idl
Here, Win32.mak is the windows32 file specifying generic settings for compiling with nmake on the Windows machine.
I ran the following commands (using the developer tools command prompt, Visual Studio 2015):
midl Example1.idl
Using the midl command, the header file Example1.h is generated, along with the stub files Example1_s.c and Example1_c.c.
Example1_s.c:
/* this ALWAYS GENERATED file contains the RPC server stubs */
/* File created by MIDL compiler version 8.01.0620 */
/* at Mon Jan 18 19:14:07 2038
*/
/* Compiler settings for Example1.idl:
Oicf, W1, Zp8, env=Win64 (32b run), target_arch=AMD64 8.01.0620
protocol : dce , ms_ext, c_ext, robust
error checks: allocation ref bounds_check enum stub_data
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
/* ##MIDL_FILE_HEADING( ) */
#if defined(_M_AMD64)
#pragma warning( disable: 4049 ) /* more than 64k source lines */
#if _MSC_VER >= 1200
#pragma warning(push)
#endif
#pragma warning( disable: 4211 ) /* redefine extern to static */
#pragma warning( disable: 4232 ) /* dllimport identity*/
#pragma warning( disable: 4024 ) /* array to pointer mapping*/
#pragma warning( disable: 4100 ) /* unreferenced arguments in x86 call */
#pragma optimize("", off )
#include <string.h>
#include "Example1.h"
#define TYPE_FORMAT_STRING_SIZE 7
#define PROC_FORMAT_STRING_SIZE 33
#define EXPR_FORMAT_STRING_SIZE 1
#define TRANSMIT_AS_TABLE_SIZE 0
#define WIRE_MARSHAL_TABLE_SIZE 0
typedef struct _Example1_MIDL_TYPE_FORMAT_STRING
{
short Pad;
unsigned char Format[ TYPE_FORMAT_STRING_SIZE ];
} Example1_MIDL_TYPE_FORMAT_STRING;
typedef struct _Example1_MIDL_PROC_FORMAT_STRING
{
short Pad;
unsigned char Format[ PROC_FORMAT_STRING_SIZE ];
} Example1_MIDL_PROC_FORMAT_STRING;
typedef struct _Example1_MIDL_EXPR_FORMAT_STRING
{
long Pad;
unsigned char Format[ EXPR_FORMAT_STRING_SIZE ];
} Example1_MIDL_EXPR_FORMAT_STRING;
static const RPC_SYNTAX_IDENTIFIER _RpcTransferSyntax =
{{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}};
extern const Example1_MIDL_TYPE_FORMAT_STRING Example1__MIDL_TypeFormatString;
extern const Example1_MIDL_PROC_FORMAT_STRING Example1__MIDL_ProcFormatString;
extern const Example1_MIDL_EXPR_FORMAT_STRING Example1__MIDL_ExprFormatString;
/* Standard interface: Example1, ver. 1.0,
GUID={0x30f190d8,0xb906,0x4699,{0x8f,0x45,0x72,0x33,0x2e,0x6a,0xd0,0x58}} */
extern const MIDL_SERVER_INFO Example1_ServerInfo;
extern const RPC_DISPATCH_TABLE Example1_v1_0_DispatchTable;
static const RPC_SERVER_INTERFACE Example1___RpcServerInterface =
{
sizeof(RPC_SERVER_INTERFACE),
{{0x30f190d8,0xb906,0x4699,{0x8f,0x45,0x72,0x33,0x2e,0x6a,0xd0,0x58}},{1,0}},
{{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}},
(RPC_DISPATCH_TABLE*)&Example1_v1_0_DispatchTable,
0,
0,
0,
&Example1_ServerInfo,
0x04000000
};
RPC_IF_HANDLE Example1_v1_0_s_ifspec = (RPC_IF_HANDLE)& Example1___RpcServerInterface;
extern const MIDL_STUB_DESC Example1_StubDesc;
#if !defined(__RPC_WIN64__)
#error Invalid build platform for this stub.
#endif
#if !(TARGET_IS_NT50_OR_LATER)
#error You need Windows 2000 or later to run this stub because it uses these features:
#error /robust command line switch.
#error However, your C/C++ compilation flags indicate you intend to run this app on earlier systems.
#error This app will fail with the RPC_X_WRONG_STUB_VERSION error.
#endif
static const Example1_MIDL_PROC_FORMAT_STRING Example1__MIDL_ProcFormatString =
{
0,
{
/* Procedure Output */
0x32, /* FC_BIND_PRIMITIVE */
0x48, /* Old Flags: */
/* 2 */ NdrFcLong( 0x0 ), /* 0 */
/* 6 */ NdrFcShort( 0x0 ), /* 0 */
/* 8 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */
/* 10 */ NdrFcShort( 0x0 ), /* 0 */
/* 12 */ NdrFcShort( 0x0 ), /* 0 */
/* 14 */ 0x42, /* Oi2 Flags: clt must size, has ext, */
0x1, /* 1 */
/* 16 */ 0xa, /* 10 */
0x1, /* Ext Flags: new corr desc, */
/* 18 */ NdrFcShort( 0x0 ), /* 0 */
/* 20 */ NdrFcShort( 0x0 ), /* 0 */
/* 22 */ NdrFcShort( 0x0 ), /* 0 */
/* 24 */ NdrFcShort( 0x0 ), /* 0 */
/* Parameter szOutput */
/* 26 */ NdrFcShort( 0x10b ), /* Flags: must size, must free, in, simple ref, */
/* 28 */ NdrFcShort( 0x0 ), /* x86 Stack size/offset = 0 */
/* 30 */ NdrFcShort( 0x4 ), /* Type Offset=4 */
0x0
}
};
static const Example1_MIDL_TYPE_FORMAT_STRING Example1__MIDL_TypeFormatString =
{
0,
{
NdrFcShort( 0x0 ), /* 0 */
/* 2 */
0x11, 0x8, /* FC_RP [simple_pointer] */
/* 4 */
0x22, /* FC_C_CSTRING */
0x5c, /* FC_PAD */
0x0
}
};
static const unsigned short Example1_FormatStringOffsetTable[] =
{
0
};
static const MIDL_STUB_DESC Example1_StubDesc =
{
(void *)& Example1___RpcServerInterface,
MIDL_user_allocate,
MIDL_user_free,
0,
0,
0,
0,
0,
Example1__MIDL_TypeFormatString.Format,
1, /* -error bounds_check flag */
0x50002, /* Ndr library version */
0,
0x801026c, /* MIDL Version 8.1.620 */
0,
0,
0, /* notify & notify_flag routine table */
0x1, /* MIDL flag */
0, /* cs routines */
0, /* proxy/server info */
0
};
static const RPC_DISPATCH_FUNCTION Example1_table[] =
{
NdrServerCall2,
0
};
static const RPC_DISPATCH_TABLE Example1_v1_0_DispatchTable =
{
1,
(RPC_DISPATCH_FUNCTION*)Example1_table
};
static const SERVER_ROUTINE Example1_ServerRoutineTable[] =
{
(SERVER_ROUTINE)Output
};
static const MIDL_SERVER_INFO Example1_ServerInfo =
{
&Example1_StubDesc,
Example1_ServerRoutineTable,
Example1__MIDL_ProcFormatString.Format,
Example1_FormatStringOffsetTable,
0,
0,
0,
0};
#if _MSC_VER >= 1200
#pragma warning(pop)
#endif
#endif /* defined(_M_AMD64)*/
Example1.h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 8.01.0620 */
/* at Mon Jan 18 19:14:07 2038
*/
/* Compiler settings for Example1.idl:
Oicf, W1, Zp8, env=Win64 (32b run), target_arch=AMD64 8.01.0620
protocol : dce , ms_ext, c_ext, robust
error checks: allocation ref bounds_check enum stub_data
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
/* ##MIDL_FILE_HEADING( ) */
#pragma warning( disable: 4049 ) /* more than 64k source lines */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif /* __RPCNDR_H_VERSION__ */
#ifndef __Example1_h__
#define __Example1_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
#ifdef __cplusplus
extern "C"{
#endif
#ifndef __Example1_INTERFACE_DEFINED__
#define __Example1_INTERFACE_DEFINED__
/* interface Example1 */
/* [implicit_handle][version][uuid] */
void Output(
/* [string][in] */ const unsigned char *szOutput);
extern handle_t hExample1Binding;
extern RPC_IF_HANDLE Example1_v1_0_c_ifspec;
extern RPC_IF_HANDLE Example1_v1_0_s_ifspec;
#endif /* __Example1_INTERFACE_DEFINED__ */
/* Additional Prototypes for ALL interfaces */
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
Next, running nmake, the following error is displayed:
link /DEBUG /DEBUGTYPE:cv /INCREMENTAL:NO /NOLOGO -subsystem:console,5.0 -out:Example1Server.exe ExampleServer.obj Example1_s.obj rpcrt4.lib kernel32.lib ws2_32.lib mswsock.lib advapi32.lib
LINK : warning LNK4010: invalid subsytem version number 5.0; default subsystem version assumed
Example1_s.obj : error LNK2001: unresolved external symbol Output
Example1Server.exe : fatal error LNK1120: 1 unresolved externals
My understanding is that the Output function is not found in Example1_s.obj. This object file is created from Example1_s.c, which is generated automatically with the midl command.
I have tried various things, such as including the header file to the link to the Example1Server, modifying the output function such that it resembles the output function in the acf file and looking around on the internet for solutions.
Most solutions found to the problems on the internet were centered around including the rpcrt4.lib, which is sadly not the solution to my problem.
I'm quite stuck at the moment, and would really appreciate it if someone can help me out in solving the LNK2001 error. Thanks in advance.
The Output function's parameter keyword in the Example1Server.cpp should be same as function declaration in the MIDL generated header file Example1.h
unsigned is missing in your case.
It should be as below in Example1Server.cpp
void Output(
/* [string][in] */ const unsigned char *szOutput)
I wrote a C++ code which I am converting to a mex file so that I can run from Matlab. My original C++ code displays output of some function declared in third party library. However, when I convert it into mex file, the output seems to be suppressed.
NOTE: output of following command get suppressed
int systemRet = std::system("./genb_test");
Original code:
#include <stdio.h> /* defines FILENAME_MAX */
#include <cstdlib>
#include <iostream>
#ifdef _MSC_VER
#include "direct.h"
#define GetCurrentDir _getcwd // window ??
#else
#include "unistd.h"
#define GetCurrentDir getcwd
#endif
int main()
{
const char *ParentFolder = "/home/dkumar/libtsnnls-2.3.3/tsnnls/";
int res3 = chdir(ParentFolder);
if (res3 == -1){
// The system method failed
std::cout<< "the chdir method has failed \n";
}
char cCurrentPath[FILENAME_MAX];
if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
{
printf("Could not find current directory " );
// return errno;
}
cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */
printf ("The current working directory is %s", cCurrentPath);
printf ("\n");
printf("Now running genb test " );
int systemRet = std::system("./genb_test");
if(systemRet == -1){
// The system method failed
}else{
printf("System command execuated successfully " );
}
return 0;
}
Output from original code:
The current working directory is /home/dkumar/libtsnnls-2.3.3/tsnnls
genb_tests
Creating 100 random test 121 x 89 problems using
the genb algorithm of PJV. Each problem will be given
to the tsnnls method, and the error printed below.
We require an error less than 1e-8 to pass the test.
# M N Error (PJV error) (Spiv error) Result
-----------------------------------------------------------------
1 121 89 1.375271e-15 1.375271e-15 0.000000e+00 pass
2 121 89 1.953126e-15 1.953126e-15 0.000000e+00 pass
3 121 89 4.272569e-15 4.272569e-15 0.000000e+00 pass
4 121 89 1.440234e-15 1.440234e-15 0.000000e+00 pass
5 121 89 2.392671e-15 2.392671e-15 0.000000e+00 pass
.......
.......
98 121 89 4.696796e-15 4.696796e-15 0.000000e+00 pass
99 121 89 1.820247e-15 1.820247e-15 0.000000e+00 pass
100 121 89 1.520109e-15 1.520109e-15 0.000000e+00 pass
100 (of 100) tests passed.
Now running genb test System command execuated successfully
Translated original code to mex file: various input and output (LHS) are left as it is, since I would start using that soon.
#include <matrix.h> // mex
#include <mex.h> // mex
#include <iostream> // Basic I/O
using namespace std; // Basic I/O
/* Definitions to keep compatibility with earlier versions of ML */
#ifndef MWSIZE_MAX
typedef int mwSize;
typedef int mwIndex;
typedef int mwSignedIndex;
#if (defined(_LP64) || defined(_WIN64)) && !defined(MX_COMPAT_32)
/* Currently 2^48 based on hardware limitations */
# define MWSIZE_MAX 281474976710655UL
# define MWINDEX_MAX 281474976710655UL
# define MWSINDEX_MAX 281474976710655L
# define MWSINDEX_MIN -281474976710655L
#else
# define MWSIZE_MAX 2147483647UL
# define MWINDEX_MAX 2147483647UL
# define MWSINDEX_MAX 2147483647L
# define MWSINDEX_MIN -2147483647L
#endif
#define MWSIZE_MIN 0UL
#define MWINDEX_MIN 0UL
#endif
// 'Hello World!' program
#include <stdio.h> /* defines FILENAME_MAX */
#include <cstdlib>
#include <iostream>
#ifdef _MSC_VER
#include "direct.h"
#define GetCurrentDir _getcwd // window ??
#else
#include "unistd.h"
#define GetCurrentDir getcwd
#endif
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
//const char *ParentFolder = "/home/dkumar/All_Matlab_Codes_DKU/";
const char *ParentFolder = "/home/dkumar/libtsnnls-2.3.3/tsnnls/";
//declare variables
mxArray *a_in_m, *b_in_m, *c_out_m, *d_out_m;
const mwSize *dims;
double *a, *b, *c, *d;
int dimx, dimy, numdims;
int i,j;
//associate inputs
a_in_m = mxDuplicateArray(prhs[0]);
b_in_m = mxDuplicateArray(prhs[1]);
//figure out dimensions
dims = mxGetDimensions(prhs[0]);
numdims = mxGetNumberOfDimensions(prhs[0]);
dimy = (int)dims[0]; dimx = (int)dims[1];
//associate outputs
c_out_m = plhs[0] = mxCreateDoubleMatrix(dimy,dimx,mxREAL);
d_out_m = plhs[1] = mxCreateDoubleMatrix(dimy,dimx,mxREAL);
//associate pointers
a = mxGetPr(a_in_m);
b = mxGetPr(b_in_m);
c = mxGetPr(c_out_m);
d = mxGetPr(d_out_m);
std::cout<< "Trying to change the directory "<< "\n";
// COPIED FROM ORIGINAL C++
int res3 = chdir(ParentFolder);
if (res3 == -1){
// The system method failed
std::cout<< "the chdir method has failed \n";
}
char cCurrentPath[FILENAME_MAX];
if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
{
printf("Could not find current directory " );
// return errno;
}
cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */
printf ("The current working directory is %s", cCurrentPath);
printf ("\n");
printf("Now running genb test " );
int systemRet = std::system("./genb_test");
if(systemRet == -1){
// The system method failed
}else{
printf("System command execuated successfully " );
}
// ADDED THIS PART at the suggestion of king_nak
//Capturing the output terminal
FILE * f = popen( "ls -al", "r" );
if ( f == 0 ) {
fprintf( stderr, "Could not execute\n" );
return;
}
const int BUFSIZE = 1000;
char buf[ BUFSIZE ];
while( fgets( buf, BUFSIZE, f ) ) {
fprintf( stdout, "%s", buf );
}
pclose( f );
return;
}
The output is:
>> [c d]=test_snnls_mex(a,b)
Trying to change the directory
The current working directory is /home/dkumar/libtsnnls-2.3.3/tsnnls
Now running genb test
c =
6 7 8
9 10 11
12 13 14
d =
1 4 9
16 25 36
49 64 81
Some help would be appreciated.
Regards,
Dushyant
std::system will start the system's command processor to execute the command. If you have a console app, this will print the output to the current console. This is why you see it in your test program. The output is not passed to the calling program!
In your case, Matlab seems to start the process in the background, where the output is discarded. Try instead opening the process and reading out its output into your program/MEX.
In POSIX, you can use popen (see for example this answer), in Windows you can use ReadPipe (cf. this article)
UPDATE
You have to adjust the code I have linked to. The original code calls ls -al and prints its output to the screen. You have to call your process genb_test!
Use this code to get the output in matlab, instead of your std::system call:
FILE * f = popen( "genb_test", "r" ); // <- call genb_test
if ( f == 0 ) {
fprintf( stderr, "Could not execute\n" );
return;
}
const int BUFSIZE = 1000;
char buf[ BUFSIZE ];
while( fgets( buf, BUFSIZE, f ) ) {
mexPrintf(buf); // <- use mexPrintf to print to matlab
}
pclose( f );
Have you tried the mex-command mexPrintf ?
However, the output won't be printed before the whole mex-program has been executed. Two work-arounds for this are to either use
mexEvalString("disp('Bla')")
or
mexPrintf("Bla")
mexEvalString("drawnow;");
I am trying to wrap c++ code to python with numpy using swig and a setup-file. I created a rather simple swig file and a setup.py, but when I run (on Windows XP)
python setup.py build -c mingw32
compilation of the shared library fails. I have no clue why, so hopefully someone can point me in the right direction.
What happens is this:
The setup-skript runs swig as it should, and a wrapped goldstein_wrap.cpp is created. Then MinGW is called, and it fails:
C:\MinGW\bin\gcc.exe -mdll -O -Wall -IC:\Programme\Python27\lib\site-packages\numpy\core\include -IC:\Programme\Python27\include -IC:\Programme\Python27\PC -c > goldstein_wrap.cpp -o build\temp.win32-2.7\Release\goldstein_wrap.o -static-libgcc -static-libstdc++
In file included from C:\Programme\Python27\lib\site-packages\numpy\core\include/numpy/ arrayobject.h:14:0,
from goldstein_wrap.cpp:3059:
C:\Programme\Python27\lib\site-packages\numpy\core\include/numpy/ndarrayobject.h:10:1:
Fehler: expected initializer before »extern«
goldstein_wrap.cpp:2954:25: Warnung: »swig_module« definiert, aber nicht verwendet
[-Wunused-variable]
error: command 'gcc' failed with exit status 1
My swig file looks like this:
%module goldstein
%{
#define SWIG_FILE_WITH_INIT
#include "goldstein.h"
%}
/*include numpy typemaps*/
%include "numpy.i"
/*initialize module*/
%init %{
import_array();
%}
%rename(unwrap2d) phase_unwrapping_func;
/* typemaps for the arrays*/
%apply (int DIM1,int DIM2,float* IN_ARRAY2) {(int ysize,int xsize,float* in)};
%apply (int DIM1,int DIM2,unsigned short* IN_ARRAY2) {(int y1,int x1,unsigned short* mask)};
%apply (int DIM1,int DIM2,float* INPLACE_ARRAY2) {(int y2,int x2,float* out),
(int y3,int x3,float* bcuts),
(int y4,int x4,float* res),
(int y5,int x5,float* diff)}
%inline %{
void phase_unwrapping_func(int ysize,int xsize,float* in,int y1,int x1,
unsigned short* mask,int y2,int x2,float* out, int y3,int x3,
float* bcuts,int y4,int x4,float* res, int y5,int x5,float* diff)
{
phase_unwrapping(xsize, ysize, in, mask, out, bcuts, res, diff);
}
%}
And to give really all information, my setup.py:
from distutils.core import setup, Extension
import numpy
try:
np_include = numpy.get_include()
except AttributeError:
np_include = numpy.get_numpy_include()
_goldstein = Extension('_goldstein',
['goldstein.i','goldstein.cpp'],
include_dirs=[np_include], #include python dll
swig_opts=['-c++'], #enable c++ wrapping
extra_compile_args=["-static-libgcc",
"-static-libstdc++"],
)
setup(name='goldstein',
version='1.1',
description='Blubb',
author='Foo',
ext_modules = [_goldstein]
)
And, as demanded, the mentioned lines of the swig-generated file:
Lines 2950 to 2958:
/* -------- TYPES TABLE (BEGIN) -------- */
#define SWIGTYPE_p_char swig_types[0]
static swig_type_info *swig_types[2];
static swig_module_info swig_module = {swig_types, 1, 0, 0, 0, 0};
#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)
#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)
/* -------- TYPES TABLE (END) -------- */
And lines 3051 to 3060:
#define SWIG_FILE_WITH_INIT
#include "goldstein.h"
#ifndef SWIG_FILE_WITH_INIT
# define NO_IMPORT_ARRAY
#endif
#include "stdio.h"
#include <numpy/arrayobject.h>
void phase_unwrapping_func(int ysize,int xsize,float* in,int y1,int x1,
unsigned short* mask,int y2,int x2,float* out,
int y3,int x3,float* bcuts,int y4,int x4,float* res,
int y5,int x5,float* diff)
{
phase_unwrapping(xsize, ysize, in, mask, out, bcuts, res, diff);
}
Line 3059 is the one including numpy/arrayobject.h. Sorry, I should have thought about that earlier...
Thanks for the hint towards the headerfile, it was a typo in the last line of that file.
Is there any debugging options built-in in the Xlib (libX11.so)? Can I get list of X11 lib calls?
I want to get full trace of xlib function calls from heavy-multithreaded, closed-source program. It is one not-public embedded platform, so I can't use gdb for multithreaded debugging and there is no ltrace on the platform.
Also, this program can't connect to x server over tcp/ip, only unix-socket. I want to do tracing of xlib calls from xlib itself.
ps. Xlib from rather modern xfree or even xorg. from gnu linux
You may be able to use xscope to monitor the requests sent over a Unix socket, even when you can't send the X protocol over TCP to be able to use network monitoring tools like Wireshark.
You might look into xlibtrace, which traces at the interface between Xlib and your code, rather than the X Windows wire protocol. I've executed a couple of the examples, and it seems to work.
The source is available at http://kev.pulo.com.au/xlibtrace
I had to modify it to get it to compile:
diff -u src/libxlibtrace-functions.h.sh.orig src/libxlibtrace-functions.h.sh
--- src/libxlibtrace-functions.h.sh.orig 2009-01-19 23:43:46.000000000 -0500
+++ src/libxlibtrace-functions.h.sh 2016-02-24 13:49:25.155556294 -0500
## -81,7 +81,7 ##
return (t ~ /^[cC][oO][nN][sS][tT][ ]/);
}
-function isarray(t) {
+function our_isarray(t) {
return (t ~ /\[.*\]$/);
}
## -90,7 +90,7 ##
return sprintf("%s", t);
} else if (isfunctionpointer(t)) {
return gensub("^(.*\\(\\*)(\\).*)$", "\\1"n"\\2", "", t);
- } else if (isarray(t)) {
+ } else if (our_isarray(t)) {
return gensub("^(.*)(\\[.*\\])$", "\\1"n"\\2", "", t);
} else {
return sprintf("%s %s", t, n);
diff -u src/libxlibtrace-print-x.h.orig src/libxlibtrace-print-x.h
--- src/libxlibtrace-print-x.h.orig 2009-01-19 22:30:06.000000000 -0500
+++ src/libxlibtrace-print-x.h 2016-02-24 14:27:08.681352710 -0500
## -2415,6 +2415,20 ##
dofflush(f);
})
+// XGenericEventCookie
+#define __REALTYPE_XGenericEventCookie__ XGenericEventCookie
+#define __REALTYPE_XGenericEventCookie_p__ XGenericEventCookie *
+#define __REALTYPE_XGenericEventCookie_pp__ XGenericEventCookie **
+#define __TRACE_PRINT_TYPE_STRUCT_BODY_XGenericEventCookie__(safetype) \
+ __TRACE_PRINT_STRUCT_MEMBER__(f, safetype, *value, int, type) __PRINT_COMMA__(f) \
+ __TRACE_PRINT_STRUCT_MEMBER__(f, safetype, *value, unsigned_long, serial) __PRINT_COMMA__(f) \
+ __TRACE_PRINT_STRUCT_MEMBER__(f, safetype, *value, Bool, send_event) __PRINT_COMMA__(f) \
+ __TRACE_PRINT_STRUCT_MEMBER__(f, safetype, *value, Display_p, display) __PRINT_COMMA__(f) \
+ __TRACE_PRINT_STRUCT_MEMBER__(f, safetype, *value, int, extension) __PRINT_COMMA__(f) \
+ __TRACE_PRINT_STRUCT_MEMBER__(f, safetype, *value, int, evtype) __PRINT_COMMA__(f) \
+ __TRACE_PRINT_STRUCT_MEMBER__(f, safetype, *value, unsigned_int, cookie) __PRINT_COMMA__(f) \
+ __TRACE_PRINT_STRUCT_MEMBER__(f, safetype, *value, void_p, data)
+__INDIRECT_CALL_3__(__TRACE_PRINT_TYPE_STRUCT,__LIBXLIBTRACE_PRINT_X_SUFF__,__)(XGenericEventCookie)
#undef __LIBXLIBTRACE_PRINT_X_BODY__