Search Results

Search found 543 results on 22 pages for 'extern'.

Page 4/22 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • C#.Net Calling a C++ DLL

    - by hayer
    Hi I got a DLL(without the sourcecode) which exports like this: ?ReceiveCoreDataPtr@@YAXPAX@Z ?xenoAddRigidBodyAngularImpulse@@YAXHMMM@Z ?xenoAddRigidBodyForce@@YAXHMMM@Z ?xenoAddRigidBodyForce@@YAXHMMMMMM@Z ?xenoAddRigidBodyLinearImpulse@@YAXHMMM@Z ?xenoAddRigidBodyPointImpulse@@YAXHMMMMMM@Z ?xenoAddRigidBodyTorque@@YAXHMMM@Z ?xenoCharacterControllerCrouch@@YAXH@Z ?xenoCharacterControllerJump@@YAXH@Z ?xenoCharacterDisable@@YAXH@Z ?xenoCharacterEnable@@YAXH@Z ?xenoDeleteRigidBody@@YAXH@Z ?xenoEnd@@YAXXZ ?xenoGetCameraFOV@@YAKH@Z ?xenoGetCameraPointX@@YAKH@Z ?xenoGetCameraPointY@@YAKH@Z ?xenoGetCameraPointZ@@YAKH@Z ?xenoGetCameraPositionX@@YAKH@Z ?xenoGetCameraPositionY@@YAKH@Z ?xenoGetCameraPositionZ@@YAKH@Z ?xenoGetCharacterControllerHeadPosition@@YAKH@Z ?xenoGetCharacterControllerPositionX@@YAKH@Z ?xenoGetCharacterControllerPositionY@@YAKH@Z ?xenoGetCharacterControllerPositionZ@@YAKH@Z ?xenoGetCharacterControllerRotation@@YAKH@Z ?xenoGetRigidBodyAllowedPenetrationDepth@@YAKH@Z ?xenoGetRigidBodyAngularDamping@@YAKH@Z ?xenoGetRigidBodyAngularVelocityX@@YAKH@Z ?xenoGetRigidBodyAngularVelocityY@@YAKH@Z ?xenoGetRigidBodyAngularVelocityZ@@YAKH@Z ?xenoGetRigidBodyFriction@@YAKH@Z ?xenoGetRigidBodyGravityFactor@@YAKH@Z ?xenoGetRigidBodyLinearDamping@@YAKH@Z ?xenoGetRigidBodyLinearVelocityX@@YAKH@Z ?xenoGetRigidBodyLinearVelocityY@@YAKH@Z ?xenoGetRigidBodyLinearVelocityZ@@YAKH@Z ?xenoGetRigidBodyMass@@YAKH@Z ?xenoGetRigidBodyMaxAngularVelocity@@YAKH@Z ?xenoGetRigidBodyMaxLinearVelocity@@YAKH@Z ?xenoGetRigidBodyPointVelocityX@@YAKHMMM@Z ?xenoGetRigidBodyPointVelocityY@@YAKHMMM@Z ?xenoGetRigidBodyPointVelocityZ@@YAKHMMM@Z ?xenoGetRigidBodyRestitution@@YAKH@Z ?xenoIsRigidBodyALadder@@YAHH@Z ?xenoMakeCamera@@YAXHH@Z ?xenoMakeCharacterController@@YAXHMM@Z ?xenoMakeCharacterController@@YAXHMMM@Z ?xenoMakeCharacterController@@YAXHMMMM@Z ?xenoMakeCharacterController@@YAXHMMMMM@Z ?xenoMakeCharacterController@@YAXHMMMMMM@Z ?xenoMakeCharacterController@@YAXHMMMMMMM@Z ?xenoMakeRigidBodyDynamicBox@@YAXH@Z ?xenoMakeRigidBodyDynamicBox@@YAXHM@Z ?xenoMakeRigidBodyDynamicCapsule@@YAXH@Z ?xenoMakeRigidBodyDynamicCapsule@@YAXHM@Z ?xenoMakeRigidBodyDynamicCylinder@@YAXH@Z ?xenoMakeRigidBodyDynamicCylinder@@YAXHM@Z ?xenoMakeRigidBodyDynamicSphere@@YAXH@Z ?xenoMakeRigidBodyDynamicSphere@@YAXHM@Z ?xenoMakeRigidBodyStaticBox@@YAXH@Z ?xenoMakeRigidBodyStaticCapsule@@YAXH@Z ?xenoMakeRigidBodyStaticCylinder@@YAXH@Z ?xenoMakeRigidBodyStaticSphere@@YAXH@Z ?xenoMakeRigidBodyStaticTriangleMesh@@YAXH@Z ?xenoMakeVehicle@@YAXHH@Z ?xenoMoveCharacterControllerBackward@@YAXH@Z ?xenoMoveCharacterControllerForward@@YAXH@Z ?xenoMoveCharacterControllerLeft@@YAXH@Z ?xenoMoveCharacterControllerRight@@YAXH@Z ?xenoSetCharacterControllerPosition@@YAXHMMM@Z ?xenoSetCharacterControllerRotation@@YAXHM@Z ?xenoSetGravity@@YAXM@Z ?xenoSetGravity@@YAXMMM@Z ?xenoSetRigidBodyAllowedPenetrationDepth@@YAXHM@Z ?xenoSetRigidBodyAngularDamping@@YAXHM@Z ?xenoSetRigidBodyAngularVelocity@@YAXHMMM@Z ?xenoSetRigidBodyAsLadder@@YAXHH@Z ?xenoSetRigidBodyFriction@@YAXHM@Z ?xenoSetRigidBodyGravityFactor@@YAXHM@Z ?xenoSetRigidBodyLinearDamping@@YAXHM@Z ?xenoSetRigidBodyLinearVelocity@@YAXHMMM@Z ?xenoSetRigidBodyMass@@YAXHM@Z ?xenoSetRigidBodyMaxAngularVelocity@@YAXHM@Z ?xenoSetRigidBodyMaxLinearVelocity@@YAXHM@Z ?xenoSetRigidBodyPosition@@YAXHMMM@Z ?xenoSetRigidBodyRestitution@@YAXHM@Z ?xenoSetRigidBodyRotation@@YAXHMMM@Z ?xenoSetTimeStep@@YAXM@Z ?xenoStart@@YAXH@Z ?xenoStart@@YAXHM@Z ?xenoStart@@YAXHMH@Z ?xenoStart@@YAXXZ ?xenoUpdate@@YAXXZ ?xenoVehicleAccelerate@@YAXHM@Z ?xenoVehicleHandbrake@@YAXH@Z ?xenoVehicleReverse@@YAXH@Z ?xenoVehicleTurn@@YAXHM@Z When I try to use it in another C++ App like this #include <windows.h> class XenoPhysics { private: typedef void (*FunctionFunc)(void); typedef void (*FunctionFuncFloat)(float); typedef void (*FunctionFuncInt)(int); typedef void (*FunctionIntFloatFloatFloat)(int,float,float,float); HMODULE libInstance; public: void LoadLib() { this->libInstance = LoadLibrary(L"F:\\xenophysics.dll"); } void UnloadLib() { FreeLibrary(libInstance); } void xStart() { FunctionFunc curFunc; curFunc = (FunctionFunc)GetProcAddress(this->libInstance, "?xenoStart@@YAXXZ"); curFunc(); } void xEnd() { FunctionFunc curFunc; curFunc = (FunctionFunc)GetProcAddress(libInstance, "xenoEnd"); curFunc(); } void xUpdate() { FunctionFunc curFunc; curFunc = (FunctionFunc)GetProcAddress(libInstance, "xenoUpdate"); curFunc(); } void xMakeRigidBodyStaticBox(int objid) { FunctionFuncInt curFunc; curFunc = (FunctionFuncInt)GetProcAddress(libInstance, "xenoMakeRigidBodyStaticBox"); curFunc(objid); } void xMakeRigidBodyDynamicBox(int objid) { FunctionFuncInt curFunc; curFunc = (FunctionFuncInt)GetProcAddress(libInstance, "xenoMakeRigidBodyDynamicBox"); curFunc(objid); } void xSetRigidBodyPosition(int objid, float x, float y, float z) { FunctionIntFloatFloatFloat curFunc; curFunc = (FunctionIntFloatFloatFloat)GetProcAddress(libInstance, "xenoSetRigidBodyPosition"); curFunc(objid, x, y, z); } void xSetGravity(float grav) { FunctionFuncFloat curFunc; curFunc = (FunctionFuncFloat)GetProcAddress(libInstance, "xenoSetGravity"); curFunc(grav); } }; This is the "wrapper"(or whatever you would call it) class.. To call the functions I'm doing XenoPhysics * d = new XenoPhysics(); d->LoadLib(); d->xStart(); It then throws the following error at me(Note that it passes the LoadLib() without any errors) Unhandled exception at 0x50261bc9 in Xeno Test.exe: 0xC0000005: Access violation reading location 0x00000064. And yes; I've checked that the "curFunc" gets the address, not just a NULL pointer(atleast I think I've checked that).. Anyone who can help out? Edit: Forgot the C#.Net code, how stupid of me :3 Here is the C++ CLR DLL "wrapper" I tried to make: #include <windows.h> // The following ifdef block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the XENOWRAPPERWIN32_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // XENOWRAPPERWIN32_API functions as being imported from a DLL, whereas this DLL sees symbols // defined with this macro as being exported. #ifdef XENOWRAPPERWIN32_EXPORTS #define XENOWRAPPERWIN32_API __declspec(dllexport) #else #define XENOWRAPPERWIN32_API __declspec(dllimport) #endif typedef void (*FunctionFunc)(); typedef void (*FunctionFuncFloat)(float); typedef void (*FunctionFuncInt)(int); typedef void (*FunctionIntFloatFloatFloat)(int,float,float,float); // This class is exported from the xeno wrapper win32.dll class XENOWRAPPERWIN32_API Cxenowrapperwin32 { public: Cxenowrapperwin32(void); HINSTANCE libInstance; // FunctionFunc curFunc; // Library base functions void LoadLib() { libInstance = LoadLibrary(L"F:\\xenophysics.dll"); } void UnloadLib() { FreeLibrary(libInstance); } // Function calls to the xeno physics void xStart() { FunctionFunc curFunc; curFunc = (FunctionFunc)GetProcAddress(libInstance, "?xenoStart@@YAXXZ"); curFunc(); } void xEnd() { FunctionFunc curFunc; curFunc = (FunctionFunc)GetProcAddress(libInstance, "?xenoEnd@@YAXXZ"); curFunc(); } void xUpdate() { FunctionFunc curFunc; curFunc = (FunctionFunc)GetProcAddress(libInstance, "?xenoUpdate@@YAXXZ"); curFunc(); } void xMakeRigidBodyStaticBox(int objid) { FunctionFuncInt curFunc; curFunc = (FunctionFuncInt)GetProcAddress(libInstance, "?xenoMakeRigidBodyStaticBox@@YAXH@Z"); curFunc(objid); } void xMakeRigidBodyDynamicBox(int objid) { FunctionFuncInt curFunc; curFunc = (FunctionFuncInt)GetProcAddress(libInstance, "?xenoMakeRigidBodyDynamicBox@@YAXH@Z"); curFunc(objid); } void xSetRigidBodyPosition(int objid, float x, float y, float z) { FunctionIntFloatFloatFloat curFunc; curFunc = (FunctionIntFloatFloatFloat)GetProcAddress(libInstance, "?xenoSetRigidBodyPosition@@YAXHMMM@Z"); curFunc(objid, x, y, z); } void xSetGravity(float grav) { FunctionFuncFloat curFunc; curFunc = (FunctionFuncFloat)GetProcAddress(libInstance, "?xenoSetGravity@@YAXM@Z"); curFunc(grav); } }; extern XENOWRAPPERWIN32_API int nxenowrapperwin32; XENOWRAPPERWIN32_API int fnxenowrapperwin32(void); and here is how I use it in C#.Net class xeno { [DllImport("C:\\Users\\hayer\\Documents\\Visual Studio 2008\\Projects\\xeno wrapper win32\\Debug\\xeno wrapper win32.dll", EntryPoint = "?LoadLib@Cxenowrapperwin32@@QAEXXZ")] public static extern void xLoadLib(); public void LoadLib() { xLoadLib(); } [DllImport("C:\\Users\\hayer\\Documents\\Visual Studio 2008\\Projects\\xeno wrapper win32\\Debug\\xeno wrapper win32.dll", EntryPoint = "?UnloadLib@Cxenowrapperwin32@@QAEXXZ")] public static extern void xUnloadLib(); public void UnloadLib() { xUnloadLib(); } [DllImport("C:\\Users\\hayer\\Documents\\Visual Studio 2008\\Projects\\xeno wrapper win32\\Debug\\xeno wrapper win32.dll", EntryPoint = "?xStart@Cxenowrapperwin32@@QAEXXZ")] public static extern void xStart(); public void Start() { xStart(); } [DllImport("C:\\Users\\hayer\\Documents\\Visual Studio 2008\\Projects\\xeno wrapper win32\\Debug\\xeno wrapper win32.dll", EntryPoint = "?xUpdate@Cxenowrapperwin32@@QAEXXZ")] public static extern void xUpdate(); public void Update() { xUpdate(); } [DllImport("C:\\Users\\hayer\\Documents\\Visual Studio 2008\\Projects\\xeno wrapper win32\\Debug\\xeno wrapper win32.dll", EntryPoint = "?xEnd@Cxenowrapperwin32@@QAEXXZ")] public static extern void xEnd(); public void End() { xEnd(); } [DllImport("C:\\Users\\hayer\\Documents\\Visual Studio 2008\\Projects\\xeno wrapper win32\\Debug\\xeno wrapper win32.dll", EntryPoint = "?xMakeRigidBodyDynamicBox@Cxenowrapperwin32@@QAEXH@Z")] public static extern void xMakeRigidBodyDynamicBox(int objid); public void MakeRigidBodyDynamicBox(int id) { xMakeRigidBodyDynamicBox(id); } [DllImport("C:\\Users\\hayer\\Documents\\Visual Studio 2008\\Projects\\xeno wrapper win32\\Debug\\xeno wrapper win32.dll", EntryPoint = "?xMakeRigidBodyStaticBox@Cxenowrapperwin32@@QAEXH@Z")] public static extern void xMakeRigidBodyStaticBox(int objid); public void MakeRigidBodyStaticBox(int id) { xMakeRigidBodyStaticBox(id); } [DllImport("C:\\Users\\hayer\\Documents\\Visual Studio 2008\\Projects\\xeno wrapper win32\\Debug\\xeno wrapper win32.dll", EntryPoint = "?xSetGravity@Cxenowrapperwin32@@QAEXM@Z")] public static extern void xSetGravity(float grav); public void SetGravity(float g) { xSetGravity(g); } [DllImport("C:\\Users\\hayer\\Documents\\Visual Studio 2008\\Projects\\xeno wrapper win32\\Debug\\xeno wrapper win32.dll", EntryPoint = "?xSetRigidBodyPosition@Cxenowrapperwin32@@QAEXHMMM@Z")] public static extern void xSetRigidBodyPosition(int obj, float x, float y, float z); public void SetRigidBodyPosition(int id, float q, float w, float e) { xSetRigidBodyPosition(id, q, w, e); } } And in the main C#.Net program I do xeno tx = new xeno(); tx.Start(); tx.SetGravity(-1); tx.MakeRigidBodyStaticBox(ground.Id); tx.MakeRigidBodyDynamicBox(cube.Id); tx.SetRigidBodyPosition(cube.Id, 0, 50, 0);

    Read the article

  • Using libgrib2c in c++ application, linker error "Undefined reference to..."

    - by Rich
    EDIT: If you're going to be doing things with GRIB files I would recommend the GDAL library which is backed by the Open Source Geospatial Foundation. You will save yourself a lot of headache :) I'm using Qt creator in Ubuntu creating a c++ app. I am attempting to use an external lib, libgrib2c.a, that has a header grib2.h. Everything compiles, but when it tries to link I get the error: undefined reference to 'seekgb(_IO_FILE*, long, long, long*, long*) I have tried wrapping the header file with: extern "C"{ #include "grib2.h" } But it didn't fix anything so I figured that was not my problem. In the .pro file I have the line: include($${ROOT}/Shared/common/commonLibs.pri) and in commonLibs.pri I have: INCLUDEPATH+=$${ROOT}/external_libs/g2clib/include LIBS+=-L$${ROOT}/external_libs/g2clib/lib LIBS+=-lgrib2c I am not encountering an error finding the library. If I do a nm command on the libgrib2c.a I get: nm libgrib2c.a | grep seekgb seekgb.o: 00000000 T seekgb And when I run qmake with the additional argument of LIBS+=-Wl,--verbose I can find the lib file in the output: attempt to open /usr/lib/libgrib2c.so failed attempt to open /usr/lib/libgrib2c.a failed attempt to open /mnt/sdb1/ESMF/App/ESMF_App/../external_libs/linux/qwt_6.0.2/lib/libgrib2c.so failed attempt to open /mnt/sdb1/ESMF/App/ESMF_App/../external_libs/linux/qwt_6.0.2/lib/libgrib2c.a failed attempt to open ..//Shared/Config/lib/libgrib2c.so failed attempt to open ..//Shared/Config/lib/libgrib2c.a failed attempt to open ..//external_libs/libssh2/lib/libgrib2c.so failed attempt to open ..//external_libs/libssh2/lib/libgrib2c.a failed attempt to open ..//external_libs/openssl/lib/libgrib2c.so failed attempt to open ..//external_libs/openssl/lib/libgrib2c.a failed attempt to open ..//external_libs/g2clib/lib/libgrib2c.so failed attempt to open ..//external_libs/g2clib/lib/libgrib2c.a succeeded Although it doesn't show any of the .o files in the library is this because it is a c library in my c++ app? in the .cpp file that I am trying to use the library I have: #include "gribreader.h" #include <stdio.h> #include <stdlib.h> #include <external_libs/g2clib/include/grib2.h> #include <Shared/logging/Logger.hpp> //------------------------------------------------------------------------------ /// Opens a GRIB file from disk. /// /// This function opens the grib file and searches through it for how many GRIB /// messages are contained as well as their starting locations. /// /// \param a_filePath. The path to the file to be opened. /// \return True if successful, false if not. //------------------------------------------------------------------------------ bool GRIBReader::OpenGRIB(std::string a_filePath) { LOG(notification)<<"Attempting to open grib file: "<< a_filePath; if(isOpen()) { CloseGRIB(); } m_filePath = a_filePath; m_filePtr = fopen(a_filePath.c_str(), "r"); if(m_filePtr == NULL) { LOG(error)<<"Unable to open file: " << a_filePath; return false; } LOG(notification)<<"Successfully opened GRIB file"; g2int currentMessageSize(1); g2int seekPosition(0); g2int lengthToBeginningOfGrib(0); g2int seekLength(32000); int i(0); int iterationLimit(300); m_GRIBMessageLocations.clear(); m_GRIBMessageSizes.clear(); while(i < iterationLimit) { seekgb(m_filePtr, seekPosition, seekLength, &lengthToBeginningOfGrib, &currentMessageSize); if(currentMessageSize != 0) { LOG(verbose) << "Adding GRIB message location " << lengthToBeginningOfGrib << " with length " << currentMessageSize; m_GRIBMessageLocations.push_back(lengthToBeginningOfGrib); m_GRIBMessageSizes.push_back(currentMessageSize); seekPosition = lengthToBeginningOfGrib + currentMessageSize; LOG(verbose) << "GRIB seek position moved to " << seekPosition; } else { LOG(notification)<<"End of GRIB file found, after "<< i << " GRIB messages."; break; } } if(i >= iterationLimit) { LOG(warning) << "The iteration limit of " << iterationLimit << "was reached while searching for GRIB messages"; } return true; } And the header grib2.h is as follows: #ifndef _grib2_H #define _grib2_H #include<stdio.h> #define G2_VERSION "g2clib-1.4.0" #ifdef __64BIT__ typedef int g2int; typedef unsigned int g2intu; #else typedef long g2int; typedef unsigned long g2intu; #endif typedef float g2float; struct gtemplate { g2int type; /* 3=Grid Defintion Template. */ /* 4=Product Defintion Template. */ /* 5=Data Representation Template. */ g2int num; /* template number. */ g2int maplen; /* number of entries in the static part */ /* of the template. */ g2int *map; /* num of octets of each entry in the */ /* static part of the template. */ g2int needext; /* indicates whether or not the template needs */ /* to be extended. */ g2int extlen; /* number of entries in the template extension. */ g2int *ext; /* num of octets of each entry in the extension */ /* part of the template. */ }; typedef struct gtemplate gtemplate; struct gribfield { g2int version,discipline; g2int *idsect; g2int idsectlen; unsigned char *local; g2int locallen; g2int ifldnum; g2int griddef,ngrdpts; g2int numoct_opt,interp_opt,num_opt; g2int *list_opt; g2int igdtnum,igdtlen; g2int *igdtmpl; g2int ipdtnum,ipdtlen; g2int *ipdtmpl; g2int num_coord; g2float *coord_list; g2int ndpts,idrtnum,idrtlen; g2int *idrtmpl; g2int unpacked; g2int expanded; g2int ibmap; g2int *bmap; g2float *fld; }; typedef struct gribfield gribfield; /* Prototypes for unpacking API */ void seekgb(FILE *,g2int ,g2int ,g2int *,g2int *); g2int g2_info(unsigned char *,g2int *,g2int *,g2int *,g2int *); g2int g2_getfld(unsigned char *,g2int ,g2int ,g2int ,gribfield **); void g2_free(gribfield *); /* Prototypes for packing API */ g2int g2_create(unsigned char *,g2int *,g2int *); g2int g2_addlocal(unsigned char *,unsigned char *,g2int ); g2int g2_addgrid(unsigned char *,g2int *,g2int *,g2int *,g2int ); g2int g2_addfield(unsigned char *,g2int ,g2int *, g2float *,g2int ,g2int ,g2int *, g2float *,g2int ,g2int ,g2int *); g2int g2_gribend(unsigned char *); /* Prototypes for supporting routines */ extern double int_power(double, g2int ); extern void mkieee(g2float *,g2int *,g2int); void rdieee(g2int *,g2float *,g2int ); extern gtemplate *getpdstemplate(g2int); extern gtemplate *extpdstemplate(g2int,g2int *); extern gtemplate *getdrstemplate(g2int); extern gtemplate *extdrstemplate(g2int,g2int *); extern gtemplate *getgridtemplate(g2int); extern gtemplate *extgridtemplate(g2int,g2int *); extern void simpack(g2float *,g2int,g2int *,unsigned char *,g2int *); extern void compack(g2float *,g2int,g2int,g2int *,unsigned char *,g2int *); void misspack(g2float *,g2int ,g2int ,g2int *, unsigned char *, g2int *); void gbit(unsigned char *,g2int *,g2int ,g2int ); void sbit(unsigned char *,g2int *,g2int ,g2int ); void gbits(unsigned char *,g2int *,g2int ,g2int ,g2int ,g2int ); void sbits(unsigned char *,g2int *,g2int ,g2int ,g2int ,g2int ); int pack_gp(g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *, g2int *); #endif /* _grib2_H */ I have been scratching my head for two days on this. If anyone has an idea on what to do or can point me in some sort of direction, I'm stumped. Also, if you have any comments on how I can improve this post I'd love to hear them, kinda new at this posting thing. Usually I'm able to find an answer in the vast stores of knowledge already contained on the web.

    Read the article

  • DLLImport error: System.AccessViolationException with Manifest file and c#

    - by RP
    When trying to call (DLLImport) an external c++ dll from a .net application that has a manifest file with requireAdministrator, I get this error trying to call function from the C++ dll in Windows 7 with UAC enabled. Method I am calling: EnCrypts System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. public class BlowFish { [DllImport("BlowfishTool.dll", CharSet = CharSet.Auto)] public static extern String EnCrypt(String strData, String strPassword); [DllImport("BlowfishTool.dll", CharSet = CharSet.Auto)] public static extern String EnCrypt(String strData, String strPassword, bool doNotUsePassChecking); [DllImport("BlowfishTool.dll", CharSet = CharSet.Auto)] public static extern String DeCrypt(String strData, String strPassword, bool doNotUsePassChecking); [DllImport("BlowfishTool.dll", CharSet = CharSet.Auto)] public static extern String DeCrypt(String strData, String strPassword); public static String EnCrypts(String strData, String strPassword) { return EnCrypt(strData, strPassword, true); } } }

    Read the article

  • adresse book with C programming, i have problem with library i think, couldn't complite my code

    - by osabri
    I've divided my code in small programm so it can be easy to excute /* ab_error.c : in case of errors following messages will be displayed */ #include "adressbook.h" static char *errormsg[] = { "", "\nNot enough space on disk", "\nCannot open file", "\nCannot read file", "\nCannot write file" }; void check(int error) { switch(error) { case 0: return; case 1: write_file(); case 2: case 3: case 4: system("cls"); fputs(errormsg[error], stderr); exit(error); } } 2nd /* ab_fileio.c : functions for file input/output */ include "adressbook.h" static char ab_file[] = "ADRESSBOOK.DAT"; //file to save the entries int read_file(void) { int error = 0; FILE *fp; ELEMENT *new_e, *last_e = NULL; DATA buffer; if( (fp = fopen(ab_file, "rb")) == NULL) return -1; //no file found while (fread(&buffer, sizeof(DATA), 1, fp) == 1) //reads one list element after another { if( (new_e = make_element()) == NULL) { error = 1; break; //not enough space } new_e->person = buffer; //copy data to new element new_e->next = NULL; if(hol.first == NULL) //list is empty? hol.first = new_e; //yes else last_e->next = new_e; //no last_e = new_e; ++hol.amount; } if( !error && !feof(fp) ) error = 3; //cannot read file fclose(fp); return error; } /-------------------------------/ int write_file(void) { int error = 0; FILE *fp; ELEMENT *p; if( (p = hol.first) == NULL) return 0; //list is empty if( (fp = fopen(ab_file, "wb")) == NULL) return 2; //cannot open while( p!= NULL) { if( fwrite(&p->person, sizeof(DATA), 1, fp) < 1) { error = 4; break; //cannot write } p = p->next; } fclose(fp); return error; } 3rd /* ab_list.c : functions to manipulate the list */ #include "adressbook.h" HOL hol = {0, NULL}; //global definition for head of list /* -------------------- */ ELEMENT *make_element(void) { return (ELEMENT *)malloc( sizeof(ELEMENT) ); } /* -------------------- */ int ins_element( DATA *newdata) { ELEMENT *new_e, *pre_p; if((new_e = make_element()) == NULL) return 1; new_e ->person = *newdata; // copy data to new element pre_p = search(new_e->person.family_name); if(pre_p == NULL) //no person in list { new_e->next = hol.first; //put it to the begin hol.first = new_e; } else { new_e->next = pre_p->next; pre_p->next = new_e; } ++hol.amount; return 0; } int erase_element( char name, char surname ) { return 0; } /* ---------------------*/ ELEMENT *search(char *name) { ELEMENT *sp, *retp; //searchpointer, returnpointer retp = NULL; sp = hol.first; while(sp != NULL && sp->person.family_name != name) { retp = sp; sp = sp->next; } return(retp); } 4th /* ab_screen.c : functions for printing information on screen */ #include "adressbook.h" #include <conio.h> #include <ctype.h> /* standard prompts for in- and output */ static char pgmname[] = "---- Oussama's Adressbook made in splendid C ----"; static char options[] = "\ 1: Enter new adress\n\n\ 2: Delete entry\n\n\ 3: Change entry\n\n\ 4: Print adress\n\n\ Esc: Exit\n\n\n\ Your choice . . .: "; static char prompt[] = "\ Name . . . .:\n\ Surname . . :\n\n\ Street . . .:\n\n\ House number:\n\n\ Postal code :\n\n\ Phone number:"; static char buttons[] = "\ <Esc> = cancel input <Backspace> = correct input\ <Return> = assume"; static char headline[] = "\ Name Surname Street House Postal code Phone number \n\ ------------------------------------------------------------------------"; static char further[] = "\ -------- continue with any key --------"; /* ---------------------------------- */ int menu(void) //show menu and read user input { int c; system ("cls"); set_cur(0,20); puts(pgmname); set_cur(6,0); printf("%s", options); while( (c = getch()) != ESC && (c < '1' || c > '4')) putch('\a'); return c; } /* ---------------------------------- */ int print_adr_book(void) //display adressbook { int line = 1; ELEMENT *p = hol.first; system("cls"); set_cur(0,20); puts(pgmname); set_cur(2,0); puts(headline); set_cur(5,0); while(p != NULL) //run through list and show entries { printf("%5d %-15s ",line, p->person.family_name); printf("%-12s %-15s ", p->person.given_name, p->person.street); printf("%-4d %-5d %-12d\n",p->person.house_number, p->person.postal_code, p->person.phone); p = p->next; if( p == NULL || ++line %16 == 1) //end of list or screen is full { set_cur(24,0); printf("%s",further); if( getch() == ESC) return 0; set_cur(5,0); scroll_up(0,5,24);//puts(headline); } } return 0; } /* -------------------------------------------*/ int make_entry(void) { char cache[50]; DATA newperson; ELEMENT *p; while(1) { system("cls"); set_cur(0,20); puts(pgmname); set_cur(6,0); puts("Please enter new data:"); set_cur(10,0); puts(prompt); set_cur(24,0); printf("%s",buttons); balken(10, 25, MAXL, ' ',0x70); //input name if(input(newperson.family_name, MAXL, ESC, CR) == ESC) return 0; balken(12,25, MAXL, ' ', 0x70); //surname if(input(newperson.given_name, MAXL, ESC, CR) == ESC) return 0; balken(14,25, 30, ' ', 0x70); //street if(input(newperson.street, 30, ESC, CR) == ESC) return 0; balken(16,25, 4, ' ',0x70); //housenumber if(input(cache, 4, ESC, CR) == ESC) return 0; newperson.house_number = atol(cache); //to string balken(18,25, 5, ' ',0x70); //postal code if(input(cache, 5, ESC, CR) == ESC) return 0; newperson.postal_code = atol(cache); //to string balken(20,25, 20, ' ',0x70); //phone number if(input(cache, 20, ESC, CR) == ESC) return 0; newperson.phone = atol(cache); //to string p = search(newperson.phone); if( p!= NULL && p->person.phone == newperson.phone) { set_cur(22,25); puts("phonenumber already exists!"); set_cur(24,0); printf("%s, further"); getch(); continue; } } } 5th /* adress_book_project.c : main program to create an adressbook */ /* copyrights by Oussama Sabri, June 2010 */ #include "adressbook.h" //project header file int main() { int rv, cmd; //return value, user command if ( (rv = read_file() ) == -1) // no data saved yet rv = make_entry(); check(rv); //prompts an error and quits program on disfunction do { switch (cmd = menu())//calls menu and gets user input back { case '1': rv = make_entry(); break; case '2': //delete entry case '3': //changes entry rv = change_entry(cmd); break; case '4': //prints adressbook on screen rv = print_adr_book(); break; case ESC: //end of program system ("cls"); rv = 0; break; } }while(cmd!= ESC); check ( write_file() ); //save adressbook return 0; } 6th /* Getcb.c --> Die Funktion getcb() liefert die naechste * * Tastatureingabe (ruft den BIOS-INT 0x16 auf). * * Return-Wert: * * ASCII-Code bzw. erweiterter Code + 256 */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> int getcb(void) { union REGS intregs; intregs.h.ah = 0; // Subfunktion 0: ein Zeichen // von der Tastatur lesen. int86( 0x16, &intregs, &intregs); if( intregs.h.al != 0) // Falls ASCII-Zeichen, return (intregs.h.al); // dieses zurueckgeben. else // Sonst den erweiterten return (intregs.h.ah + 0x100); // Code + 256 } 7th /* PUTCB.C --> enthaelt die Funktionen * * - putcb() * * - putcb9() * * - balken() * * - input() * * * * Es werden die Funktionen 9 und 14 des Video-Interrupts * * (ROM-BIOS-Interrupt 0x10) verwendet. * * * * Die Prototypen dieser Funktionen stehen in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #define VIDEO_INT 0x10 /*---------------------------------------------------------------- * putcb(c) gibt das Zeichen auf der aktuellen Cursor-Position * am Bildschirm aus. Der Cursor wird versetzt. * Steuerzeichen Back-Space, CR, LF und BELL werden * ausgefuehrt. * Return-Wert: keiner */ void putcb(unsigned char c) /* Gibt das Zeichen in c auf */ { /* den Bildschirm aus. */ union REGS intregs; intregs.h.ah = 14; /* Subfunktion 14 ("Teletype") */ intregs.h.al = c; intregs.h.bl = 0xf; /* Vordergrund-Farbe im */ /* Grafik-Modus. */ int86(VIDEO_INT, &intregs, &intregs); } /*---------------------------------------------------------------- * putcb9(c,count,mode) gibt das Zeichen in c count-mal im * angegebenen Modus auf der aktuellen * Cursor-Position am Bildschirm aus. * Der Cursor wird nicht versetzt. * * Return-Wert: keiner */ void putcb9( unsigned char c, /* das Zeichen */ unsigned count, /* die Anzahl */ unsigned mode ) /* Low-Byte: das Atrribut */ { /* High-Byte: die Bildschirmseite*/ union REGS intregs; intregs.h.ah = 9; /* Subfunktion 9 des Int 0x10 */ intregs.h.al = c; intregs.x.bx = mode; intregs.x.cx = count; int86( VIDEO_INT, &intregs, &intregs); } /*---------------------------------------------------------------- * balken() positioniert den Cursor und zeichnet einen Balken, * wobei Position, L„nge, Fllzeichen und Attribut * als Argumente bergeben werden. * Der Cursor bleibt auf der ersten Position im Balken. */ void balken( unsigned int zeile, /* Start-Position */ unsigned int spalte, unsigned int laenge, /* Laenge des Balkens */ unsigned char c, /* Fuellzeichen */ unsigned int modus) /* Low-Byte: Attribut */ /* High-Byte: Bildschirmseite */ { union REGS intregs; intregs.h.ah = 2; /* Cursor auf der angegebenen */ intregs.h.dh = zeile; /* Bildschirmseite versetzen. */ intregs.h.dl = spalte; intregs.h.bh = (modus >> 8); int86(VIDEO_INT, &intregs, &intregs); putcb9(c, laenge, modus); /* Balken ausgeben. */ } /*---------------------------------------------------------------- * input() liest Zeichen von der Tastatur ein und haengt '\0' an. * Mit Backspace kann die Eingabe geloescht werden. * Das Attribut am Bildschirm bleibt erhalten. * * Argumente: 1. Zeiger auf den Eingabepuffer. * 2. Anzahl maximal einzulesender Zeichen. * 3. Die optionalen Argumente: Zeichen, mit denen die * Eingabe abgebrochen werden kann. * Diese Liste muá mit CR = '\r' enden! * Return-Wert: Das Zeichen, mit dem die Eingabe abgebrochen wurde. */ #include <stdarg.h> int getcb( void); /* Zum Lesen der Tastatur */ int input(char *puffer, int max,... ) { int c; /* aktuelles Zeichen */ int breakc; /* Abruchzeichen */ int nc = 0; /* Anzahl eingelesener Zeichen */ va_list argp; /* Zeiger auf die weiteren Arumente */ while(1) { *puffer = '\0'; va_start(argp, max); /* argp initialisieren */ c = getcb(); do /* Mit Zeichen der Abbruchliste vergleichen */ if(c == (breakc = va_arg(argp,int)) ) return(breakc); while( breakc != '\r' ); va_end( argp); if( c == '\b' && nc > 0) /* Backspace? */ { --nc; --puffer; putcb(c); putcb(' '); putcb(c); } else if( c >= 32 && c <= 255 && nc < max ) { ++nc; *puffer++ = c; putcb(c); } else if( nc == max) putcb('\7'); /* Ton ausgeben */ } } 8th /* Video.c --> Enthaelt die Funktionen * cls(), * scroll_up(), scroll_down(), * set_cur(), get_cur(), * set_screen_page(), get_screen_page() * * Die Prototypen dieser Funktionen befinden sich in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #include "bio.h" #define VIDEO_INT 0x10 typedef unsigned char BYTE; void scroll_up( int anzahl, int anf_zeile, int end_zeile) { /* Fenster hoch rollen. */ union REGS intregs; intregs.x.ax = 0x600 + anzahl; /* Subfunktion AH = 6, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void scroll_down( int anzahl, int anf_zeile, int end_zeile) { /* Fenster runter rollen. */ union REGS intregs; intregs.x.ax = 0x700 + anzahl; /* Subfunktion AH = 7, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void set_cur( int zeile, int spalte) /* versetzt den Cursor */ { /* der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 2; intregs.h.dh = (BYTE)zeile; intregs.h.dl = (BYTE)spalte; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); } void get_cur(int *zeile, int *spalte) /* holt die Cursor- */ { /* Position der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 3; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); *zeile = (unsigned)intregs.h.dh; *spalte = (unsigned)intregs.h.dl; } void cls(void) { scroll_up(0,0,24); /* Gesamten Bildschirm loeschen. */ set_cur(0,0); /* Cursor in Home-Position. */ } int get_screen_page(void) /* Aktuelle Bildschirmseite holen.*/ { union REGS intregs; intregs.h.ah = 15; /* Subfunktion AH = 15: */ /* Bildschirm-Modus feststellen. */ int86(VIDEO_INT, &intregs, &intregs); return (intregs.h.bh); } void set_screen_page(int seite) /* setzt die aktive Seite des */ { /* Bildschirmpuffers auf die */ /* angegebene Seite. */ union REGS intregs; intregs.x.ax = 0x500 + seite; /* Subfunktion AH = 5 */ int86(VIDEO_INT, &intregs, &intregs); } /* ------------------------------------------------------------- Ein kleines Testprogramm : */ /* #include <stdio.h> int main() { cls(); set_cur(23, 0); printf("Weiter mit <Return>\n"); set_cur(12, 20); printf("Ein Test!\n"); getchar(); scroll_up(3, 5, 20); getchar(); scroll_down(6, 5, 20); getchar(); set_screen_page(1); printf("\nAuf der 2. Seite !\n"); getchar(); set_screen_page(0); set_cur(0,0); printf("\nWieder auf der 1. Seite !\n"); getchar(); cls(); return 0; } */ /* Video.c --> Enthaelt die Funktionen * cls(), * scroll_up(), scroll_down(), * set_cur(), get_cur(), * set_screen_page(), get_screen_page() * * Die Prototypen dieser Funktionen befinden sich in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #include "bio.h" #define VIDEO_INT 0x10 typedef unsigned char BYTE; void scroll_up( int anzahl, int anf_zeile, int end_zeile) { /* Fenster hoch rollen. */ union REGS intregs; intregs.x.ax = 0x600 + anzahl; /* Subfunktion AH = 6, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void scroll_down( int anzahl, int anf_zeile, int end_zeile) { /* Fenster runter rollen. */ union REGS intregs; intregs.x.ax = 0x700 + anzahl; /* Subfunktion AH = 7, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void set_cur( int zeile, int spalte) /* versetzt den Cursor */ { /* der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 2; intregs.h.dh = (BYTE)zeile; intregs.h.dl = (BYTE)spalte; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); } void get_cur(int *zeile, int *spalte) /* holt die Cursor- */ { /* Position der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 3; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); *zeile = (unsigned)intregs.h.dh; *spalte = (unsigned)intregs.h.dl; } void cls(void) { scroll_up(0,0,24); /* Gesamten Bildschirm loeschen. */ set_cur(0,0); /* Cursor in Home-Position. */ } int get_screen_page(void) /* Aktuelle Bildschirmseite holen.*/ { union REGS intregs; intregs.h.ah = 15; /* Subfunktion AH = 15: */ /* Bildschirm-Modus feststellen. */ int86(VIDEO_INT, &intregs, &intregs); return (intregs.h.bh); } void set_screen_page(int seite) /* setzt die aktive Seite des */ { /* Bildschirmpuffers auf die */ /* angegebene Seite. */ union REGS intregs; intregs.x.ax = 0x500 + seite; /* Subfunktion AH = 5 */ int86(VIDEO_INT, &intregs, &intregs); } /* ------------------------------------------------------------- Ein kleines Testprogramm : */ /* #include <stdio.h> int main() { cls(); set_cur(23, 0); printf("Weiter mit <Return>\n"); set_cur(12, 20); printf("Ein Test!\n"); getchar(); scroll_up(3, 5, 20); getchar(); scroll_down(6, 5, 20); getchar(); set_screen_page(1); printf("\nAuf der 2. Seite !\n"); getchar(); set_screen_page(0); set_cur(0,0); printf("\nWieder auf der 1. Seite !\n"); getchar(); cls(); return 0; } */ /* BIO.H --> Enthaelt die Prototypen der BIOS-Funktionen. */ /* --- Funktionen in VIDEO.C --- */ extern void scroll_up(int anzahl, int anf_zeile,int end_zeile); extern void scroll_down(int anzahl, int anf_zeile, int end_zeile); extern void set_cur(int zeile, int spalte); extern void get_cur(int *zeile, int *spalte); extern void cls(void); extern int get_screen_page(void); extern void set_screen_page(int page); /* --- Funktionen in GETCB.C / PUTCB.C --- */ extern int getcb(void); extern void putcb(int c); extern void putcb9(int c, unsigned count, unsigned modus); extern void balken(int zeile, int spalte, int laenge, int c, unsigned modus); extern int input(char *puffer, int max,... ); need your help, can't find my mistakes:((

    Read the article

  • Reference a GNU C (POSIX) DLL built in GCC against Cygwin, from C#/NET

    - by Dale Halliwell
    Here is what I want: I have a huge legacy C/C++ codebase written for POSIX, including some very POSIX specific stuff like pthreads. This can be compiled on Cygwin/GCC and run as an executable under Windows with the Cygwin DLL. What I would like to do is build the codebase itself into a Windows DLL that I can then reference from C# and write a wrapper around it to access some parts of it programatically. I have tried this approach with the very simple "hello world" example at http://www.cygwin.com/cygwin-ug-net/dll.html and it doesn't seem to work. #include <stdio.h> extern "C" __declspec(dllexport) int hello(); int hello() { printf ("Hello World!\n"); return 42; } I believe I should be able to reference a DLL built with the above code in C# using something like: [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllToLoad); [DllImport("kernel32.dll")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); [DllImport("kernel32.dll")] public static extern bool FreeLibrary(IntPtr hModule); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int hello(); static void Main(string[] args) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "helloworld.dll"); IntPtr pDll = LoadLibrary(path); IntPtr pAddressOfFunctionToCall = GetProcAddress(pDll, "hello"); hello hello = (hello)Marshal.GetDelegateForFunctionPointer( pAddressOfFunctionToCall, typeof(hello)); int theResult = hello(); Console.WriteLine(theResult.ToString()); bool result = FreeLibrary(pDll); Console.ReadKey(); } But this approach doesn't seem to work. LoadLibrary returns null. It can find the DLL (helloworld.dll), it is just like it can't load it or find the exported function. I am sure that if I get this basic case working I can reference the rest of my codebase in this way. Any suggestions or pointers, or does anyone know if what I want is even possible? Thanks. Edit: Examined my DLL with Dependency Walker (great tool, thanks) and it seems to export the function correctly. Question: should I be referencing it as the function name Dependency Walker seems to find (_Z5hellov)? Edit2: Just to show you I have tried it, linking directly to the dll at relative or absolute path (i.e. not using LoadLibrary): [DllImport(@"C:\.....\helloworld.dll")] public static extern int hello(); static void Main(string[] args) { int theResult = hello(); Console.WriteLine(theResult.ToString()); Console.ReadKey(); } This fails with: "Unable to load DLL 'C:.....\helloworld.dll': Invalid access to memory location. (Exception from HRESULT: 0x800703E6) *Edit 3: * Oleg has suggested running dumpbin.exe on my dll, this is the output: Dump of file helloworld.dll File Type: DLL Section contains the following exports for helloworld.dll 00000000 characteristics 4BD5037F time date stamp Mon Apr 26 15:07:43 2010 0.00 version 1 ordinal base 1 number of functions 1 number of names ordinal hint RVA name 1 0 000010F0 hello Summary 1000 .bss 1000 .data 1000 .debug_abbrev 1000 .debug_info 1000 .debug_line 1000 .debug_pubnames 1000 .edata 1000 .eh_frame 1000 .idata 1000 .reloc 1000 .text Edit 4 Thanks everyone for the help, I managed to get it working. Oleg's answer gave me the information I needed to find out what I was doing wrong. There are 2 ways to do this. One is to build with the gcc -mno-cygwin compiler flag, which builds the dll without the cygwin dll, basically as if you had built it in MingW. Building it this way got my hello world example working! However, MingW doesn't have all the libraries that cygwin has in the installer, so if your POSIX code has dependencies on these libraries (mine had heaps) you can't do this way. And if your POSIX code didn't have those dependencies, why not just build for Win32 from the beginning. So that's not much help unless you want to spend time setting up MingW properly. The other option is to build with the Cygwin DLL. The Cygwin DLL needs an initialization function init() to be called before it can be used. This is why my code wasn't working before. The code below loads and runs my hello world example. //[DllImport(@"hello.dll", EntryPoint = "#1",SetLastError = true)] //static extern int helloworld(); //don't do this! cygwin needs to be init first [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32", SetLastError = true)] static extern IntPtr LoadLibrary(string lpFileName); public delegate int MyFunction(); static void Main(string[] args) { //load cygwin dll IntPtr pcygwin = LoadLibrary("cygwin1.dll"); IntPtr pcyginit = GetProcAddress(pcygwin, "cygwin_dll_init"); Action init = (Action)Marshal.GetDelegateForFunctionPointer(pcyginit, typeof(Action)); init(); IntPtr phello = LoadLibrary("hello.dll"); IntPtr pfn = GetProcAddress(phello, "helloworld"); MyFunction helloworld = (MyFunction)Marshal.GetDelegateForFunctionPointer(pfn, typeof(MyFunction)); Console.WriteLine(helloworld()); Console.ReadKey(); } Thanks to everyone that answered~~

    Read the article

  • Address book with C programming; cannot compile my code.

    - by osabri
    I've divided my code into small programs so it can be easy to excute /* ab_error.c : in case of errors following messages will be displayed */ #include "adressbook.h" static char *errormsg[] = { "", "\nNot enough space on disk", "\nCannot open file", "\nCannot read file", "\nCannot write file" }; void check(int error) { switch(error) { case 0: return; case 1: write_file(); case 2: case 3: case 4: system("cls"); fputs(errormsg[error], stderr); exit(error); } } 2nd /* ab_fileio.c : functions for file input/output */ #include "adressbook.h" static char ab_file[] = "ADRESSBOOK.DAT"; //file to save the entries int read_file(void) { int error = 0; FILE *fp; ELEMENT *new_e, *last_e = NULL; DATA buffer; if( (fp = fopen(ab_file, "rb")) == NULL) return -1; //no file found while (fread(&buffer, sizeof(DATA), 1, fp) == 1) //reads one list element after another { if( (new_e = make_element()) == NULL) { error = 1; break; //not enough space } new_e->person = buffer; //copy data to new element new_e->next = NULL; if(hol.first == NULL) //list is empty? hol.first = new_e; //yes else last_e->next = new_e; //no last_e = new_e; ++hol.amount; } if( !error && !feof(fp) ) error = 3; //cannot read file fclose(fp); return error; } /*-------------------------------*/ int write_file(void) { int error = 0; FILE *fp; ELEMENT *p; if( (p = hol.first) == NULL) return 0; //list is empty if( (fp = fopen(ab_file, "wb")) == NULL) return 2; //cannot open while( p!= NULL) { if( fwrite(&p->person, sizeof(DATA), 1, fp) < 1) { error = 4; break; //cannot write } p = p->next; } fclose(fp); return error; } 3rd /* ab_list.c : functions to manipulate the list */ #include "adressbook.h" HOL hol = {0, NULL}; //global definition for head of list /* -------------------- */ ELEMENT *make_element(void) { return (ELEMENT *)malloc( sizeof(ELEMENT) ); } /* -------------------- */ int ins_element( DATA *newdata) { ELEMENT *new_e, *pre_p; if((new_e = make_element()) == NULL) return 1; new_e ->person = *newdata; // copy data to new element pre_p = search(new_e->person.family_name); if(pre_p == NULL) //no person in list { new_e->next = hol.first; //put it to the begin hol.first = new_e; } else { new_e->next = pre_p->next; pre_p->next = new_e; } ++hol.amount; return 0; } int erase_element( char name, char surname ) { return 0; } /* ---------------------*/ ELEMENT *search(char *name) { ELEMENT *sp, *retp; //searchpointer, returnpointer retp = NULL; sp = hol.first; while(sp != NULL && sp->person.family_name != name) { retp = sp; sp = sp->next; } return(retp); } 4th /* ab_screen.c : functions for printing information on screen */ #include "adressbook.h" #include <conio.h> #include <ctype.h> /* standard prompts for in- and output */ static char pgmname[] = "---- Oussama's Adressbook made in splendid C ----"; static char options[] = "\ 1: Enter new adress\n\n\ 2: Delete entry\n\n\ 3: Change entry\n\n\ 4: Print adress\n\n\ Esc: Exit\n\n\n\ Your choice . . .: "; static char prompt[] = "\ Name . . . .:\n\ Surname . . :\n\n\ Street . . .:\n\n\ House number:\n\n\ Postal code :\n\n\ Phone number:"; static char buttons[] = "\ <Esc> = cancel input <Backspace> = correct input\ <Return> = assume"; static char headline[] = "\ Name Surname Street House Postal code Phone number \n\ ------------------------------------------------------------------------"; static char further[] = "\ -------- continue with any key --------"; /* ---------------------------------- */ int menu(void) //show menu and read user input { int c; system ("cls"); set_cur(0,20); puts(pgmname); set_cur(6,0); printf("%s", options); while( (c = getch()) != ESC && (c < '1' || c > '4')) putch('\a'); return c; } /* ---------------------------------- */ int print_adr_book(void) //display adressbook { int line = 1; ELEMENT *p = hol.first; system("cls"); set_cur(0,20); puts(pgmname); set_cur(2,0); puts(headline); set_cur(5,0); while(p != NULL) //run through list and show entries { printf("%5d %-15s ",line, p->person.family_name); printf("%-12s %-15s ", p->person.given_name, p->person.street); printf("%-4d %-5d %-12d\n",p->person.house_number, p->person.postal_code, p->person.phone); p = p->next; if( p == NULL || ++line %16 == 1) //end of list or screen is full { set_cur(24,0); printf("%s",further); if( getch() == ESC) return 0; set_cur(5,0); scroll_up(0,5,24);//puts(headline); } } return 0; } /* -------------------------------------------*/ int make_entry(void) { char cache[50]; DATA newperson; ELEMENT *p; while(1) { system("cls"); set_cur(0,20); puts(pgmname); set_cur(6,0); puts("Please enter new data:"); set_cur(10,0); puts(prompt); set_cur(24,0); printf("%s",buttons); balken(10, 25, MAXL, ' ',0x70); //input name if(input(newperson.family_name, MAXL, ESC, CR) == ESC) return 0; balken(12,25, MAXL, ' ', 0x70); //surname if(input(newperson.given_name, MAXL, ESC, CR) == ESC) return 0; balken(14,25, 30, ' ', 0x70); //street if(input(newperson.street, 30, ESC, CR) == ESC) return 0; balken(16,25, 4, ' ',0x70); //housenumber if(input(cache, 4, ESC, CR) == ESC) return 0; newperson.house_number = atol(cache); //to string balken(18,25, 5, ' ',0x70); //postal code if(input(cache, 5, ESC, CR) == ESC) return 0; newperson.postal_code = atol(cache); //to string balken(20,25, 20, ' ',0x70); //phone number if(input(cache, 20, ESC, CR) == ESC) return 0; newperson.phone = atol(cache); //to string p = search(newperson.phone); if( p!= NULL && p->person.phone == newperson.phone) { set_cur(22,25); puts("phonenumber already exists!"); set_cur(24,0); printf("%s, further"); getch(); continue; } } } 5th /* adress_book_project.c : main program to create an adressbook */ /* copyrights by Oussama Sabri, June 2010 */ #include "adressbook.h" //project header file int main() { int rv, cmd; //return value, user command if ( (rv = read_file() ) == -1) // no data saved yet rv = make_entry(); check(rv); //prompts an error and quits program on disfunction do { switch (cmd = menu())//calls menu and gets user input back { case '1': rv = make_entry(); break; case '2': //delete entry case '3': //changes entry rv = change_entry(cmd); break; case '4': //prints adressbook on screen rv = print_adr_book(); break; case ESC: //end of program system ("cls"); rv = 0; break; } }while(cmd!= ESC); check ( write_file() ); //save adressbook return 0; } 6th /* Getcb.c --> Die Funktion getcb() liefert die naechste * * Tastatureingabe (ruft den BIOS-INT 0x16 auf). * * Return-Wert: * * ASCII-Code bzw. erweiterter Code + 256 */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> int getcb(void) { union REGS intregs; intregs.h.ah = 0; // Subfunktion 0: ein Zeichen // von der Tastatur lesen. int86( 0x16, &intregs, &intregs); if( intregs.h.al != 0) // Falls ASCII-Zeichen, return (intregs.h.al); // dieses zurueckgeben. else // Sonst den erweiterten return (intregs.h.ah + 0x100); // Code + 256 } 7th /* PUTCB.C --> enthaelt die Funktionen * * - putcb() * * - putcb9() * * - balken() * * - input() * * * * Es werden die Funktionen 9 und 14 des Video-Interrupts * * (ROM-BIOS-Interrupt 0x10) verwendet. * * * * Die Prototypen dieser Funktionen stehen in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #define VIDEO_INT 0x10 /*---------------------------------------------------------------- * putcb(c) gibt das Zeichen auf der aktuellen Cursor-Position * am Bildschirm aus. Der Cursor wird versetzt. * Steuerzeichen Back-Space, CR, LF und BELL werden * ausgefuehrt. * Return-Wert: keiner */ void putcb(unsigned char c) /* Gibt das Zeichen in c auf */ { /* den Bildschirm aus. */ union REGS intregs; intregs.h.ah = 14; /* Subfunktion 14 ("Teletype") */ intregs.h.al = c; intregs.h.bl = 0xf; /* Vordergrund-Farbe im */ /* Grafik-Modus. */ int86(VIDEO_INT, &intregs, &intregs); } /*---------------------------------------------------------------- * putcb9(c,count,mode) gibt das Zeichen in c count-mal im * angegebenen Modus auf der aktuellen * Cursor-Position am Bildschirm aus. * Der Cursor wird nicht versetzt. * * Return-Wert: keiner */ void putcb9( unsigned char c, /* das Zeichen */ unsigned count, /* die Anzahl */ unsigned mode ) /* Low-Byte: das Atrribut */ { /* High-Byte: die Bildschirmseite*/ union REGS intregs; intregs.h.ah = 9; /* Subfunktion 9 des Int 0x10 */ intregs.h.al = c; intregs.x.bx = mode; intregs.x.cx = count; int86( VIDEO_INT, &intregs, &intregs); } /*---------------------------------------------------------------- * balken() positioniert den Cursor und zeichnet einen Balken, * wobei Position, L„nge, Fllzeichen und Attribut * als Argumente bergeben werden. * Der Cursor bleibt auf der ersten Position im Balken. */ void balken( unsigned int zeile, /* Start-Position */ unsigned int spalte, unsigned int laenge, /* Laenge des Balkens */ unsigned char c, /* Fuellzeichen */ unsigned int modus) /* Low-Byte: Attribut */ /* High-Byte: Bildschirmseite */ { union REGS intregs; intregs.h.ah = 2; /* Cursor auf der angegebenen */ intregs.h.dh = zeile; /* Bildschirmseite versetzen. */ intregs.h.dl = spalte; intregs.h.bh = (modus >> 8); int86(VIDEO_INT, &intregs, &intregs); putcb9(c, laenge, modus); /* Balken ausgeben. */ } /*---------------------------------------------------------------- * input() liest Zeichen von der Tastatur ein und haengt '\0' an. * Mit Backspace kann die Eingabe geloescht werden. * Das Attribut am Bildschirm bleibt erhalten. * * Argumente: 1. Zeiger auf den Eingabepuffer. * 2. Anzahl maximal einzulesender Zeichen. * 3. Die optionalen Argumente: Zeichen, mit denen die * Eingabe abgebrochen werden kann. * Diese Liste muá mit CR = '\r' enden! * Return-Wert: Das Zeichen, mit dem die Eingabe abgebrochen wurde. */ #include <stdarg.h> int getcb( void); /* Zum Lesen der Tastatur */ int input(char *puffer, int max,... ) { int c; /* aktuelles Zeichen */ int breakc; /* Abruchzeichen */ int nc = 0; /* Anzahl eingelesener Zeichen */ va_list argp; /* Zeiger auf die weiteren Arumente */ while(1) { *puffer = '\0'; va_start(argp, max); /* argp initialisieren */ c = getcb(); do /* Mit Zeichen der Abbruchliste vergleichen */ if(c == (breakc = va_arg(argp,int)) ) return(breakc); while( breakc != '\r' ); va_end( argp); if( c == '\b' && nc > 0) /* Backspace? */ { --nc; --puffer; putcb(c); putcb(' '); putcb(c); } else if( c >= 32 && c <= 255 && nc < max ) { ++nc; *puffer++ = c; putcb(c); } else if( nc == max) putcb('\7'); /* Ton ausgeben */ } } 8th /* Video.c --> Enthaelt die Funktionen * cls(), * scroll_up(), scroll_down(), * set_cur(), get_cur(), * set_screen_page(), get_screen_page() * * Die Prototypen dieser Funktionen befinden sich in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #include "bio.h" #define VIDEO_INT 0x10 typedef unsigned char BYTE; void scroll_up( int anzahl, int anf_zeile, int end_zeile) { /* Fenster hoch rollen. */ union REGS intregs; intregs.x.ax = 0x600 + anzahl; /* Subfunktion AH = 6, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void scroll_down( int anzahl, int anf_zeile, int end_zeile) { /* Fenster runter rollen. */ union REGS intregs; intregs.x.ax = 0x700 + anzahl; /* Subfunktion AH = 7, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void set_cur( int zeile, int spalte) /* versetzt den Cursor */ { /* der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 2; intregs.h.dh = (BYTE)zeile; intregs.h.dl = (BYTE)spalte; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); } void get_cur(int *zeile, int *spalte) /* holt die Cursor- */ { /* Position der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 3; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); *zeile = (unsigned)intregs.h.dh; *spalte = (unsigned)intregs.h.dl; } void cls(void) { scroll_up(0,0,24); /* Gesamten Bildschirm loeschen. */ set_cur(0,0); /* Cursor in Home-Position. */ } int get_screen_page(void) /* Aktuelle Bildschirmseite holen.*/ { union REGS intregs; intregs.h.ah = 15; /* Subfunktion AH = 15: */ /* Bildschirm-Modus feststellen. */ int86(VIDEO_INT, &intregs, &intregs); return (intregs.h.bh); } void set_screen_page(int seite) /* setzt die aktive Seite des */ { /* Bildschirmpuffers auf die */ /* angegebene Seite. */ union REGS intregs; intregs.x.ax = 0x500 + seite; /* Subfunktion AH = 5 */ int86(VIDEO_INT, &intregs, &intregs); } /* ------------------------------------------------------------- Ein kleines Testprogramm : */ /* #include <stdio.h> int main() { cls(); set_cur(23, 0); printf("Weiter mit <Return>\n"); set_cur(12, 20); printf("Ein Test!\n"); getchar(); scroll_up(3, 5, 20); getchar(); scroll_down(6, 5, 20); getchar(); set_screen_page(1); printf("\nAuf der 2. Seite !\n"); getchar(); set_screen_page(0); set_cur(0,0); printf("\nWieder auf der 1. Seite !\n"); getchar(); cls(); return 0; } */ /* Video.c --> Enthaelt die Funktionen * cls(), * scroll_up(), scroll_down(), * set_cur(), get_cur(), * set_screen_page(), get_screen_page() * * Die Prototypen dieser Funktionen befinden sich in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #include "bio.h" #define VIDEO_INT 0x10 typedef unsigned char BYTE; void scroll_up( int anzahl, int anf_zeile, int end_zeile) { /* Fenster hoch rollen. */ union REGS intregs; intregs.x.ax = 0x600 + anzahl; /* Subfunktion AH = 6, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void scroll_down( int anzahl, int anf_zeile, int end_zeile) { /* Fenster runter rollen. */ union REGS intregs; intregs.x.ax = 0x700 + anzahl; /* Subfunktion AH = 7, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void set_cur( int zeile, int spalte) /* versetzt den Cursor */ { /* der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 2; intregs.h.dh = (BYTE)zeile; intregs.h.dl = (BYTE)spalte; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); } void get_cur(int *zeile, int *spalte) /* holt die Cursor- */ { /* Position der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 3; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); *zeile = (unsigned)intregs.h.dh; *spalte = (unsigned)intregs.h.dl; } void cls(void) { scroll_up(0,0,24); /* Gesamten Bildschirm loeschen. */ set_cur(0,0); /* Cursor in Home-Position. */ } int get_screen_page(void) /* Aktuelle Bildschirmseite holen.*/ { union REGS intregs; intregs.h.ah = 15; /* Subfunktion AH = 15: */ /* Bildschirm-Modus feststellen. */ int86(VIDEO_INT, &intregs, &intregs); return (intregs.h.bh); } void set_screen_page(int seite) /* setzt die aktive Seite des */ { /* Bildschirmpuffers auf die */ /* angegebene Seite. */ union REGS intregs; intregs.x.ax = 0x500 + seite; /* Subfunktion AH = 5 */ int86(VIDEO_INT, &intregs, &intregs); } /* ------------------------------------------------------------- Ein kleines Testprogramm : */ /* #include <stdio.h> int main() { cls(); set_cur(23, 0); printf("Weiter mit <Return>\n"); set_cur(12, 20); printf("Ein Test!\n"); getchar(); scroll_up(3, 5, 20); getchar(); scroll_down(6, 5, 20); getchar(); set_screen_page(1); printf("\nAuf der 2. Seite !\n"); getchar(); set_screen_page(0); set_cur(0,0); printf("\nWieder auf der 1. Seite !\n"); getchar(); cls(); return 0; } */ /* BIO.H --> Enthaelt die Prototypen der BIOS-Funktionen. */ /* --- Funktionen in VIDEO.C --- */ extern void scroll_up(int anzahl, int anf_zeile,int end_zeile); extern void scroll_down(int anzahl, int anf_zeile, int end_zeile); extern void set_cur(int zeile, int spalte); extern void get_cur(int *zeile, int *spalte); extern void cls(void); extern int get_screen_page(void); extern void set_screen_page(int page); /* --- Funktionen in GETCB.C / PUTCB.C --- */ extern int getcb(void); extern void putcb(int c); extern void putcb9(int c, unsigned count, unsigned modus); extern void balken(int zeile, int spalte, int laenge, int c, unsigned modus); extern int input(char *puffer, int max,... ); need your help, can't find my mistakes:((

    Read the article

  • How to hide/show a Process using c#?

    - by aF
    Hello, While executing my program, I want to hide/minimize Microsoft Speech Recognition Application: and at the end I want to show/maximize using c#! This process is not started by me so I can't give control the process startInfo. I've tried to use user32.dll methods such as: ShowWindow AnimatedWindows AnimatedWindows With all of them I have the same problem. I can hide the windows (althought I have to call one of the methods two times with SW_HIDE option), but when I call the method with a SW_SHOW flag, it simply doesn't shows.. How can I maximize/show after hiding the process? Thanks in advance! Here is some pieces of the code, now implemented to use SetWindowPlacement: { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl); [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl); [DllImport("user32.dll")] public static extern Boolean ShowWindowAsync(IntPtr hWnd, Int32 nCmdShow); [DllImport("user32.dll")] public static extern Boolean SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow); [DllImport("user32.dll")] public static extern Boolean AnimateWindow(IntPtr hWnd, uint dwTime, uint dwFlags); [DllImport("dwmapi.dll")] public static extern int DwmSetWindowAttribute(IntPtr hwnd, uint dwAttribute, IntPtr pvAttribute, IntPtr lol); //Definitions For Different Window Placement Constants const UInt32 SW_HIDE = 0; const UInt32 SW_SHOWNORMAL = 1; const UInt32 SW_NORMAL = 1; const UInt32 SW_SHOWMINIMIZED = 2; const UInt32 SW_SHOWMAXIMIZED = 3; const UInt32 SW_MAXIMIZE = 3; const UInt32 SW_SHOWNOACTIVATE = 4; const UInt32 SW_SHOW = 5; const UInt32 SW_MINIMIZE = 6; const UInt32 SW_SHOWMINNOACTIVE = 7; const UInt32 SW_SHOWNA = 8; const UInt32 SW_RESTORE = 9; public sealed class AnimateWindowFlags { public const int AW_HOR_POSITIVE = 0x00000001; public const int AW_HOR_NEGATIVE = 0x00000002; public const int AW_VER_POSITIVE = 0x00000004; public const int AW_VER_NEGATIVE = 0x00000008; public const int AW_CENTER = 0x00000010; public const int AW_HIDE = 0x00010000; public const int AW_ACTIVATE = 0x00020000; public const int AW_SLIDE = 0x00040000; public const int AW_BLEND = 0x00080000; } public struct WINDOWPLACEMENT { public int length; public int flags; public int showCmd; public System.Drawing.Point ptMinPosition; public System.Drawing.Point ptMaxPosition; public System.Drawing.Rectangle rcNormalPosition; } //this works param = new WINDOWPLACEMENT(); param.length = Marshal.SizeOf(typeof(WINDOWPLACEMENT)); param.showCmd = (int)SW_HIDE; lol = SetWindowPlacement(theprocess.MainWindowHandle, ref param); // this doesn't work WINDOWPLACEMENT param = new WINDOWPLACEMENT(); param.length = Marshal.SizeOf(typeof(WINDOWPLACEMENT)); param.showCmd = SW_SHOW; lol = GetWindowPlacement(theprocess.MainWindowHandle, ref param);

    Read the article

  • Unable to Calculate Position within Owner-Draw Text

    - by Jonathan Wood
    I'm trying to use Visual Studio 2012 to create a Windows Forms application that can place the caret at the current position within a owner-drawn string. However, I've been unable to find a way to accurately calculate that position. I've done this successfully before in C++. I've now tried numerous methods in C#. Originally, I tried using .NET classes to determine the correct position, but then I tried accessing the Windows API directly. In some cases, I came close, but after some time I still cannot place the caret accurately. I've created a small test program and posted key parts below. I've also posted the entire project here. The exact font used is not important to me; however, my application assumes a mono-spaced font. Any help is appreciated. Form1.cs This is my main form. public partial class Form1 : Form { private string TestString; private int AveCharWidth; private int Position; public Form1() { InitializeComponent(); TestString = "123456789012345678901234567890123456789012345678901234567890"; AveCharWidth = GetFontWidth(); Position = 0; } private void Form1_Load(object sender, EventArgs e) { Font = new Font(FontFamily.GenericMonospace, 12, FontStyle.Regular, GraphicsUnit.Pixel); } protected override void OnGotFocus(EventArgs e) { Windows.CreateCaret(Handle, (IntPtr)0, 2, (int)Font.Height); Windows.ShowCaret(Handle); UpdateCaretPosition(); base.OnGotFocus(e); } protected void UpdateCaretPosition() { Windows.SetCaretPos(Padding.Left + (Position * AveCharWidth), Padding.Top); } protected override void OnLostFocus(EventArgs e) { Windows.HideCaret(Handle); Windows.DestroyCaret(); base.OnLostFocus(e); } protected override void OnPaint(PaintEventArgs e) { e.Graphics.DrawString(TestString, Font, SystemBrushes.WindowText, new PointF(Padding.Left, Padding.Top)); } protected override bool IsInputKey(Keys keyData) { switch (keyData) { case Keys.Right: case Keys.Left: return true; } return base.IsInputKey(keyData); } protected override void OnKeyDown(KeyEventArgs e) { switch (e.KeyCode) { case Keys.Left: Position = Math.Max(Position - 1, 0); UpdateCaretPosition(); break; case Keys.Right: Position = Math.Min(Position + 1, TestString.Length); UpdateCaretPosition(); break; } base.OnKeyDown(e); } protected int GetFontWidth() { int AverageCharWidth = 0; using (var graphics = this.CreateGraphics()) { try { Windows.TEXTMETRIC tm; var hdc = graphics.GetHdc(); IntPtr hFont = this.Font.ToHfont(); IntPtr hOldFont = Windows.SelectObject(hdc, hFont); var a = Windows.GetTextMetrics(hdc, out tm); var b = Windows.SelectObject(hdc, hOldFont); var c = Windows.DeleteObject(hFont); AverageCharWidth = tm.tmAveCharWidth; } catch { } finally { graphics.ReleaseHdc(); } } return AverageCharWidth; } } Windows.cs Here are my Windows API declarations. public static class Windows { [Serializable, StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct TEXTMETRIC { public int tmHeight; public int tmAscent; public int tmDescent; public int tmInternalLeading; public int tmExternalLeading; public int tmAveCharWidth; public int tmMaxCharWidth; public int tmWeight; public int tmOverhang; public int tmDigitizedAspectX; public int tmDigitizedAspectY; public short tmFirstChar; public short tmLastChar; public short tmDefaultChar; public short tmBreakChar; public byte tmItalic; public byte tmUnderlined; public byte tmStruckOut; public byte tmPitchAndFamily; public byte tmCharSet; } [DllImport("user32.dll")] public static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight); [DllImport("User32.dll")] public static extern bool SetCaretPos(int x, int y); [DllImport("User32.dll")] public static extern bool DestroyCaret(); [DllImport("User32.dll")] public static extern bool ShowCaret(IntPtr hWnd); [DllImport("User32.dll")] public static extern bool HideCaret(IntPtr hWnd); [DllImport("gdi32.dll", CharSet = CharSet.Auto)] public static extern bool GetTextMetrics(IntPtr hdc, out TEXTMETRIC lptm); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("GDI32.dll")] public static extern bool DeleteObject(IntPtr hObject); }

    Read the article

  • How to remove the MenuBar of an application using windows API ?

    - by karthik
    I am using the below code to remove the Title Bar of an application, which is working perfectly for notepad. Now i want to remove the Menu Bar also. How to achieve it ? //Finds a window by class name [DllImport("USER32.DLL")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); //Sets a window to be a child window of another window [DllImport("USER32.DLL")] public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); //Sets window attributes [DllImport("USER32.DLL")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); //Gets window attributes [DllImport("USER32.DLL")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName); //assorted constants needed public static int GWL_STYLE = -16; public static int WS_BORDER = 0x00800000; //window with border public static int WS_DLGFRAME = 0x00400000; //window with double border but no title public static int WS_CAPTION = WS_BORDER | WS_DLGFRAME; //window with a title bar public void WindowsReStyle() { Process[] Procs = Process.GetProcesses(); foreach (Process proc in Procs) { if (proc.ProcessName.StartsWith("notepad")) { IntPtr pFoundWindow = proc.MainWindowHandle; int style = GetWindowLong(pFoundWindow, GWL_STYLE); SetWindowLong(pFoundWindow, GWL_STYLE, (style & ~WS_CAPTION)); } } }

    Read the article

  • Problem invoking C DLL in C#

    - by CristiC
    I'm currently trying to invoke a method made in C from C# C code looks like this: extern "C" int addSum(int a, int b) { return a*b; } extern "C" int getCount() { return 12; } and C# code looks like this: [DllImport("mydll.dll", SetLastError=true)] private static extern int addSum(IntPtr a, IntPtr b); [DllImport("mydll.dll", SetLastError = true)] private static extern int getCount(); public static int mySum(int a, int b) { return suma(a, b); } public static int getMyCount() { return getCount(); } The code returns the right values but i'm getting the following error: addSum' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature. Any sugestion regarding this issue ? Thanks

    Read the article

  • About using assembly with c

    - by kristus
    Hi. I've sort of just finished a mandatory task at school, and I'm about to deliver it. But then I came across something that was unfamiliar, header files. :( What I've got: test-program.c task_header.h function1.s function2.s function3.s function4.s test-program.c: #include <stdio.h> #include <stdlib.h> #include <string.h> #include "task_header.h" . .. ... task_header.h: extern void function1(...); extern void function2(...); extern int function3(...); extern void function4(...); And then I use the command: gcc -m32 -o runtest test-program.c function1.s function2.s function3.s function4.s Is this a proper way to do it, or is it possible to modify it? So I can type: gcc -m32 -o runtest test-program.c ?

    Read the article

  • How to drag widgets from monitor to monitor in kubuntu?

    - by Mien
    I have Kubuntu 12.04 on my Dell Inspiron. I use an extern monitor as my default one, and my laptop monitor as my second monitor. I can place widgets on the extern (default) screen, but when I drag them to the laptop (second) screen, they disappear. I can put widgets on the second screen, if I open the widget screen on that screen, but I can't drag them to my first monitor. How can I switch between monitors for the widgets?

    Read the article

  • Extended FindWindow

    - by João Angelo
    The Win32 API provides the FindWindow function that supports finding top-level windows by their class name and/or title. However, the title search does not work if you are trying to match partial text at the middle or the end of the full window title. You can however implement support for these extended search features by using another set of Win32 API like EnumWindows and GetWindowText. A possible implementation follows: using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; public class WindowInfo { private IntPtr handle; private string className; internal WindowInfo(IntPtr handle, string title) { if (handle == IntPtr.Zero) throw new ArgumentException("Invalid handle.", "handle"); this.Handle = handle; this.Title = title ?? string.Empty; } public string Title { get; private set; } public string ClassName { get { if (className == null) { className = GetWindowClassNameByHandle(this.Handle); } return className; } } public IntPtr Handle { get { if (!NativeMethods.IsWindow(this.handle)) throw new InvalidOperationException("The handle is no longer valid."); return this.handle; } private set { this.handle = value; } } public static WindowInfo[] EnumerateWindows() { var windows = new List<WindowInfo>(); NativeMethods.EnumWindowsProcessor processor = (hwnd, lParam) => { windows.Add(new WindowInfo(hwnd, GetWindowTextByHandle(hwnd))); return true; }; bool succeeded = NativeMethods.EnumWindows(processor, IntPtr.Zero); if (!succeeded) return new WindowInfo[] { }; return windows.ToArray(); } public static WindowInfo FindWindow(Predicate<WindowInfo> predicate) { WindowInfo target = null; NativeMethods.EnumWindowsProcessor processor = (hwnd, lParam) => { var current = new WindowInfo(hwnd, GetWindowTextByHandle(hwnd)); if (predicate(current)) { target = current; return false; } return true; }; NativeMethods.EnumWindows(processor, IntPtr.Zero); return target; } private static string GetWindowTextByHandle(IntPtr handle) { if (handle == IntPtr.Zero) throw new ArgumentException("Invalid handle.", "handle"); int length = NativeMethods.GetWindowTextLength(handle); if (length == 0) return string.Empty; var buffer = new StringBuilder(length + 1); NativeMethods.GetWindowText(handle, buffer, buffer.Capacity); return buffer.ToString(); } private static string GetWindowClassNameByHandle(IntPtr handle) { if (handle == IntPtr.Zero) throw new ArgumentException("Invalid handle.", "handle"); const int WindowClassNameMaxLength = 256; var buffer = new StringBuilder(WindowClassNameMaxLength); NativeMethods.GetClassName(handle, buffer, buffer.Capacity); return buffer.ToString(); } } internal class NativeMethods { public delegate bool EnumWindowsProcessor(IntPtr hwnd, IntPtr lParam); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumWindows( EnumWindowsProcessor lpEnumFunc, IntPtr lParam); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern int GetWindowText( IntPtr hWnd, StringBuilder lpString, int nMaxCount); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern int GetClassName( IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWindow(IntPtr hWnd); } The access to the windows handle is preceded by a sanity check to assert if it’s still valid, but if you are dealing with windows out of your control then the window can be destroyed right after the check so it’s not guaranteed that you’ll get a valid handle. Finally, to wrap this up a usage, example: static void Main(string[] args) { var w = WindowInfo.FindWindow(wi => wi.Title.Contains("Test.docx")); if (w != null) { Console.Write(w.Title); } }

    Read the article

  • Xen 4.2 on CentOs 6.3 : can't compile a libvirt 0.9.10 xen-activated?

    - by Frederic
    I followed that tutorial for Xen 4.2 on CentOs 6.3. http://www.howtoforge.com/virtualization-with-xen-on-centos-6.3-x86_64-paravirtualization-and-hardware-virtualization When building a new libvirt package with rpmbuild -bb libvirt.spec I get that error : CC libvirt_driver_libxl_la-libxl_conf.lo In file included from libxl/libxl_conf.c:43: libxl/libxl_conf.h:61: error: field 'ctx' has incomplete type libxl/libxl_conf.h:80: error: field 'ctx' has incomplete type libxl/libxl_conf.h:81: error: expected specifier-qualifier-list before 'libxl_waiter' libxl/libxl_conf.c: In function 'libxlMakeDomCreateInfo': libxl/libxl_conf.c:365: warning: implicit declaration of function 'libxl_init_create_info' [-Wimplicit-function-declaration] libxl/libxl_conf.c:365: warning: nested extern declaration of 'libxl_init_create_info' [-Wnested-externs] libxl/libxl_conf.c:367: error: 'libxl_domain_create_info' has no member named 'hvm' libxl/libxl_conf.c:383: warning: implicit declaration of function 'libxl_domain_create_info_destroy' [-Wimplicit-function-declaration] libxl/libxl_conf.c:383: warning: nested extern declaration of 'libxl_domain_create_info_destroy' [-Wnested-externs] libxl/libxl_conf.c: In function 'libxlMakeDomBuildInfo': libxl/libxl_conf.c:406: warning: implicit declaration of function 'libxl_init_build_info' [-Wimplicit-function-declaration] libxl/libxl_conf.c:406: warning: nested extern declaration of 'libxl_init_build_info' [-Wnested-externs] libxl/libxl_conf.c:408: error: 'libxl_domain_build_info' has no member named 'hvm' [...] Do you know what I need to install or change to pass that step?

    Read the article

  • Dynamic libraries are not allowed on iOS but what about this?

    - by tapirath
    I'm currently using LuaJIT and its FFI interface to call C functions from LUA scripts. What FFI does is to look at dynamic libraries' exported symbols and let the developer use it directly form LUA. Kind of like Python ctypes. Obviously using dynamic libraries is not permitted in iOS for security reasons. So in order to come up with a solution I found the following snippet. /* (c) 2012 +++ Filip Stoklas, aka FipS, http://www.4FipS.com +++ THIS CODE IS FREE - LICENSED UNDER THE MIT LICENSE ARTICLE URL: http://forums.4fips.com/viewtopic.php?f=3&t=589 */ extern "C" { #include <lua.h> #include <lualib.h> #include <lauxlib.h> } // extern "C" #include <cassert> // Please note that despite the fact that we build this code as a regular // executable (exe), we still use __declspec(dllexport) to export // symbols. Without doing that FFI wouldn't be able to locate them! extern "C" __declspec(dllexport) void __cdecl hello_from_lua(const char *msg) { printf("A message from LUA: %s\n", msg); } const char *lua_code = "local ffi = require('ffi') \n" "ffi.cdef[[ \n" "const char * hello_from_lua(const char *); \n" // matches the C prototype "]] \n" "ffi.C.hello_from_lua('Hello from LUA!') \n" // do actual C call ; int main() { lua_State *lua = luaL_newstate(); assert(lua); luaL_openlibs(lua); const int status = luaL_dostring(lua, lua_code); if(status) printf("Couldn't execute LUA code: %s\n", lua_tostring(lua, -1)); lua_close(lua); return 0; } // output: // A message from LUA: Hello from LUA! Basically, instead of using a dynamic library, the symbols are exported directly inside the executable file. The question is: is this permitted by Apple? Thanks.

    Read the article

  • I don't understand how work call_once

    - by SABROG
    Please help me understand how work call_once Here is thread-safe code. I don't understand why this need Thread Local Storage and global_epoch variables. Variable _fast_pthread_once_per_thread_epoch can be changed to constant/enum like {FAST_PTHREAD_ONCE_INIT, BEING_INITIALIZED, FINISH_INITIALIZED}. Why needed count calls in global_epoch? I think this code can be rewriting with logc: if flag FINISH_INITIALIZED do nothing, else go to block with mutexes and this all. #ifndef FAST_PTHREAD_ONCE_H #define FAST_PTHREAD_ONCE_H #include #include typedef sig_atomic_t fast_pthread_once_t; #define FAST_PTHREAD_ONCE_INIT SIG_ATOMIC_MAX extern __thread fast_pthread_once_t _fast_pthread_once_per_thread_epoch; #ifdef __cplusplus extern "C" { #endif extern void fast_pthread_once( pthread_once_t *once, void (*func)(void) ); inline static void fast_pthread_once_inline( fast_pthread_once_t *once, void (*func)(void) ) { fast_pthread_once_t x = *once; /* unprotected access */ if ( x _fast_pthread_once_per_thread_epoch ) { fast_pthread_once( once, func ); } } #ifdef __cplusplus } #endif #endif FAST_PTHREAD_ONCE_H Source fast_pthread_once.c The source is written in C. The lines of the primary function are numbered for reference in the subsequent correctness argument. #include "fast_pthread_once.h" #include static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER; /* protects global_epoch and all fast_pthread_once_t writes */ static pthread_cond_t cv = PTHREAD_COND_INITIALIZER; /* signalled whenever a fast_pthread_once_t is finalized */ #define BEING_INITIALIZED (FAST_PTHREAD_ONCE_INIT - 1) static fast_pthread_once_t global_epoch = 0; /* under mu */ __thread fast_pthread_once_t _fast_pthread_once_per_thread_epoch; static void check( int x ) { if ( x == 0 ) abort(); } void fast_pthread_once( fast_pthread_once_t *once, void (*func)(void) ) { /*01*/ fast_pthread_once_t x = *once; /* unprotected access */ /*02*/ if ( x _fast_pthread_once_per_thread_epoch ) { /*03*/ check( pthread_mutex_lock(µ) == 0 ); /*04*/ if ( *once == FAST_PTHREAD_ONCE_INIT ) { /*05*/ *once = BEING_INITIALIZED; /*06*/ check( pthread_mutex_unlock(µ) == 0 ); /*07*/ (*func)(); /*08*/ check( pthread_mutex_lock(µ) == 0 ); /*09*/ global_epoch++; /*10*/ *once = global_epoch; /*11*/ check( pthread_cond_broadcast(&cv;) == 0 ); /*12*/ } else { /*13*/ while ( *once == BEING_INITIALIZED ) { /*14*/ check( pthread_cond_wait(&cv;, µ) == 0 ); /*15*/ } /*16*/ } /*17*/ _fast_pthread_once_per_thread_epoch = global_epoch; /*18*/ check (pthread_mutex_unlock(µ) == 0); } } This code from BOOST: #ifndef BOOST_THREAD_PTHREAD_ONCE_HPP #define BOOST_THREAD_PTHREAD_ONCE_HPP // once.hpp // // (C) Copyright 2007-8 Anthony Williams // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include #include #include #include "pthread_mutex_scoped_lock.hpp" #include #include #include namespace boost { struct once_flag { boost::uintmax_t epoch; }; namespace detail { BOOST_THREAD_DECL boost::uintmax_t& get_once_per_thread_epoch(); BOOST_THREAD_DECL extern boost::uintmax_t once_global_epoch; BOOST_THREAD_DECL extern pthread_mutex_t once_epoch_mutex; BOOST_THREAD_DECL extern pthread_cond_t once_epoch_cv; } #define BOOST_ONCE_INITIAL_FLAG_VALUE 0 #define BOOST_ONCE_INIT {BOOST_ONCE_INITIAL_FLAG_VALUE} // Based on Mike Burrows fast_pthread_once algorithm as described in // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2444.html template void call_once(once_flag& flag,Function f) { static boost::uintmax_t const uninitialized_flag=BOOST_ONCE_INITIAL_FLAG_VALUE; static boost::uintmax_t const being_initialized=uninitialized_flag+1; boost::uintmax_t const epoch=flag.epoch; boost::uintmax_t& this_thread_epoch=detail::get_once_per_thread_epoch(); if(epoch #endif I right understand, boost don't use atomic operation, so code from boost not thread-safe?

    Read the article

  • Using C code in c#

    - by karthik
    When i googled to find the way to change the window style i could find the code in "C" language How can i use the snippet below in my c# application, so that i can hide the Title Bar of external application ? I have not used "C" before.. //Finds a window by class name [DllImport("USER32.DLL")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); //Sets a window to be a child window of another window [DllImport("USER32.DLL")] public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); //Sets window attributes [DllImport("USER32.DLL")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); //Gets window attributes [DllImport("USER32.DLL")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); //assorted constants needed public static int GWL_STYLE = -16; public static int WS_CHILD = 0x40000000; //child window public static int WS_BORDER = 0x00800000; //window with border public static int WS_DLGFRAME = 0x00400000; //window with double border but no title public static int WS_CAPTION= WS_BORDER | WS_DLGFRAME; //window with a title bar /* This function sets the parent of the window with class ClassClass to the form/control the method is in. */ public void Reparent() { //get handle of parent form (.net property) IntPtr par = this.Handle; //get handle of child form (win32) IntPtr child = FindWindow("ClassClass", null); //set parent of child form SetParent(child, par); //get current window style of child form int style = GetWindowLong(child, GWL_STYLE); //take current window style and remove WS_CAPTION from it SetWindowLong(child, GWL_STYLE, (style & ~WS_CAPTION)); }

    Read the article

  • Managed .NET Equivalent to CreateFile & WriteFile from WinBase (kernel32.dll)

    - by StevenH
    I am working with a legacy file format. The file is created using unmanaged C++ that utilizes the WinBase.h CreateFile() & WriteFile() functions (found in the kernel32.dll). I have been using P/Invoke interop to access these native functions like so: [DllImport("kernel32.dll")] public static extern bool WriteFile( IntPtr hFile, byte[] lpBuffer, uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten, [In] ref NativeOverlapped lpOverlapped); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool WriteFileEx( IntPtr hFile, byte[] lpBuffer, uint nNumberOfBytesToWrite, [In] ref NativeOverlapped lpOverlapped, WriteFileCompletionDelegate lpCompletionRoutine); [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr CreateFile( string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool CloseHandle(IntPtr hObject); public delegate void WriteFileCompletionDelegate( UInt32 dwErrorCode, UInt32 dwNumberOfBytesTransfered, ref NativeOverlapped lpOverlapped); The issue with this is when I call WriteFile(), the file is always overwritten by the proceeding call. I need to find a compatible .NET equivalent that would allow me to produce the exact same format of output. Thanks.

    Read the article

  • Assign C++ instance method to a global-function-pointer ?

    - by umanga
    Greetings, My project structure is as follows: \- base (C static library) callbacks.h callbacks.c paint_node.c . . * libBase.a \-app (C++ application) main.cpp In C library 'base' , I have declared global-function-pointer as: in singleheader file callbacks.h #ifndef CALLBACKS_H_ #define CALLBACKS_H_ extern void (*putPixelCallBack)(); extern void (*putImageCallBack)(); #endif /* CALLBACKS_H_ */ in single C file they are initialized as callbacks.c #include "callbacks.h" void (*putPixelCallBack)(); void (*putImageCallBack)(); Other C files access this callback-functions as: paint_node.c #include "callbacks.h" void paint_node(node *node,int index){ //Call callbackfunction . . putPixelCallBack(node->x,node->y,index); } I compile these C files and generate a static library 'libBase.a' Then in C++ application, I want to assign C++ instance method to this global function-pointer: I did something like follows : in Sacm.cpp file #include "Sacm.h" extern void (*putPixelCallBack)(); extern void (*putImageCallBack)(); void Sacm::doDetection() { putPixelCallBack=(void(*)())&paintPixel; //call somefunctions in 'libBase' C library } void Sacm::paintPixel(int x,int y,int index) { qpainter.begin(this); qpainter.drawPoint(x,y); qpainter.end(); } But when compiling it gives the error: sacmtest.cpp: In member function ‘void Sacm::doDetection()’: sacmtest.cpp:113: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say ‘&Sacm::paintPixel’ sacmtest.cpp:113: error: converting from ‘void (Sacm::)(int, int, int)’ to ‘void ()()’ Any tips?

    Read the article

  • C callback functions defined in an unnamed namespace?

    - by Johannes Schaub - litb
    Hi all. I have a C++ project that uses a C bison parser. The C parser uses a struct of function pointers to call functions that create proper AST nodes when productions are reduced by bison: typedef void Node; struct Actions { Node *(*newIntLit)(int val); Node *(*newAsgnExpr)(Node *left, Node *right); /* ... */ }; Now, in the C++ part of the project, i fill those pointers class AstNode { /* ... */ }; class IntLit : public AstNode { /* ... */ }; extern "C" { Node *newIntLit(int val) { return (Node*)new IntLit(val); } /* ... */ } Actions createActions() { Actions a; a.newIntLit = &newIntLit; /* ... */ return a; } Now the only reason i put them within extern "C" is because i want them to have C calling conventions. But optimally, i would like their names still be mangled. They are never called by-name from C code, so name mangling isn't an issue. Having them mangled will avoid name conflicts, since some actions are called like error, and the C++ callback function has ugly names like the following just to avoid name clashes with other modules. extern "C" { void uglyNameError(char const *str) { /* ... */ } /* ... */ } a.error = &uglyNameError; I wondered whether it could be possible by merely giving the function type C linkage extern "C" void fty(char const *str); namespace { fty error; /* Declared! But i can i define it with that type!? */ } Any ideas? I'm looking for Standard-C++ solutions.

    Read the article

  • Reference a GNU C DLL built in GCC against Cygwin, from C#/NET

    - by Dale Halliwell
    Here is what I want: I have a huge legacy C/C++ codebase written for POSIX, including some very POSIX specific stuff like pthreads. This can be compiled on Cygwin/GCC and run as an executable under Windows with the Cygwin DLL. What I would like to do is build the codebase itself into a Windows DLL that I can then reference from C# and write a wrapper around it to access some parts of it programatically. I have tried this approach with the very simple "hello world" example at http://www.cygwin.com/cygwin-ug-net/dll.html and it doesn't seem to work. #include <stdio.h> extern "C" __declspec(dllexport) int hello(); int hello() { printf ("Hello World!\n"); return 42; } I believe I should be able to reference a DLL built with the above code in C# using something like: [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllToLoad); [DllImport("kernel32.dll")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); [DllImport("kernel32.dll")] public static extern bool FreeLibrary(IntPtr hModule); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int hello(); static void Main(string[] args) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "helloworld.dll"); IntPtr pDll = LoadLibrary(path); IntPtr pAddressOfFunctionToCall = GetProcAddress(pDll, "hello"); hello hello = (hello)Marshal.GetDelegateForFunctionPointer( pAddressOfFunctionToCall, typeof(hello)); int theResult = hello(); Console.WriteLine(theResult.ToString()); bool result = FreeLibrary(pDll); Console.ReadKey(); } But this approach doesn't seem to work. LoadLibrary returns null. It can find the DLL (helloworld.dll), it is just like it can't load it or find the exported function. I am sure that if I get this basic case working I can reference the rest of my codebase in this way. Any suggestions or pointers, or does anyone know if what I want is even possible? Thanks.

    Read the article

  • Enumeration trouble: redeclared as different kind of symbol

    - by Matt
    Hello all. I am writing a program that is supposed to help me learn about enumeration data types in C++. The current trouble is that the compiler doesn't like my enum usage when trying to use the new data type as I would other data types. I am getting the error "redeclared as different kind of symbol" when compiling my trangleShape function. Take a look at the relevant code. Any insight is appreciated! Thanks! (All functions are their own .cpp files.) header file #ifndef HEADER_H_INCLUDED #define HEADER_H_INCLUDED #include <iostream> #include <iomanip> using namespace std; enum triangleType {noTriangle, scalene, isoceles, equilateral}; //prototypes void extern input(float&, float&, float&); triangleType extern triangleShape(float, float, float); /*void extern output (float, float, float);*/ void extern myLabel(const char *, const char *); #endif // HEADER_H_INCLUDED main function //8.1 main // this progam... #include "header.h" int main() { float sideLength1, sideLength2, sideLength3; char response; do //main loop { input (sideLength1, sideLength2, sideLength3); triangleShape (sideLength1, sideLength2, sideLength3); //output (sideLength1, sideLength2, sideLength3); cout << "\nAny more triangles to analyze? (y,n) "; cin >> response; } while (response == 'Y' || response == 'y'); myLabel ("8.1", "2/11/2011"); return 0; } triangleShape shape # include "header.h" triangleType triangleShape(sideLenght1, sideLength2, sideLength3) { triangleType triangle; return triangle; }

    Read the article

  • C++ STL: How to write wrappers for cout, cerr, cin and endl?

    - by Ashwin
    I do not like using namespace std, but I am also tired of having to type std:: in front of every cout, cin, cerr and endl. So, I thought of giving them shorter new names like this: // STLWrapper.h #include <iostream> #include <string> extern std::ostream& Cout; extern std::ostream& Cerr; extern std::istream& Cin; extern std::string& Endl; // STLWrapper.cpp #include "STLWrapper.h" std::ostream& Cout = std::cout; std::ostream& Cerr = std::cerr; std::istream& Cerr = std::cin; std::string _EndlStr("\n"); std::string& Endl = _EndlStr; This works. But, are there any problems in the above which I am missing? Is there a better way to achieve the same?

    Read the article

  • [C++] Trouble declaring and recognizing global functions

    - by Sarah
    I've created some mathematical functions that will be used in main() and by member functions in multiple host classes. I was thinking it would be easiest to make these math functions global in scope, but I'm not sure how to do this. I've currently put all the functions in a file called Rdraws.cpp, with the prototypes in Rdraws.h. Even with all the #includes and externs, I'm getting a "symbol not found" error at the first function call in main(). Here's what I have: // Rdraws.cpp #include <cstdlib> using namespace std; #include <cmath> #include "Rdraws.h" #include "rng.h" extern RNG rgen // this is the PRNG used in the simulation; global scope void rmultinom( double p_trans[], int numTrials, int numTrans, int numEachTrans[] ) { // function 1 def } void rmultinom( const double p_trans[], const int numTrials, int numTrans, int numEachTrans[]) { // function 2 def } int rbinom( int nTrials, double pLeaving ) { // function 3 def } // Rdraws.h #ifndef RDRAWS #define RDRAWS void rmultinom( double[], int, int, int[] ); void rmultinom( const double[], const int, int, int[] ); int rbinom( int, double ); #endif // main.cpp ... #include "Rdraws.h" ... extern void rmultinom(double p_trans[], int numTrials, int numTrans, int numEachTrans[]); extern void rmultinom(const double p_trans[], const int numTrials, int numTrans, int numEachTrans[]); extern int rbinom( int n, double p ); ... int main() { ... } I'm pretty new to programming. If there's a dramatically smarter way to do this, I'd love to know.

    Read the article

  • Importing a C DLL's functions into a C++ program

    - by bobobobo
    I have a 3rd party library that's written in C. It exports all of its functions to a DLL. I have the .h file, and I'm trying to load the DLL from my C++ program. The first thing I tried was surrounding the parts where I #include the 3rd party lib in #ifdef __cplusplus extern "C" { #endif and, at the end #ifdef __cplusplus } // extern "C" #endif But the problem there was, all of the DLL file function linkage looked like this in their header files: a_function = (void *)GetProcAddress(dll, "a_function"); While really a_function had type int (*a_function) (int *). Apparently MSVC++ compiler doesn't like this, while MSVC compiler does not seem to mind. So I went through (brutal torture) and fixed them all to the pattern typedef int (*_a_function) (int *); _a_function a_function ; Then, to link it to the DLL code, in main(): a_function = (_a_function)GetProcAddress(dll, "a_function"); This SEEMS to make the compiler MUCH, MUCH happier, but it STILL complains with this final set of 143 errors, each saying for each of the DLL link attempts: error LNK2005: _a_function already defined in main.obj main.obj Multiple symbol definition errors.. sounds like a job for extern! SO I went and made ALL the function pointer declarations as follows: function_pointers.h typedef int (*_a_function) (int *); extern _a_function a_function ; And in a cpp file: function_pointers.cpp #include "function_pointers.h" _a_function a_function ; ALL fine and dandy.. except for linker errors now of the form: error LNK2001: unresolved external symbol _a_function main.obj Main.cpp includes "function_pointers.h", so it should know where to find each of the functions.. I am bamboozled. Does any one have any pointers to get me functional? (Pardon the pun..)

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >