중복 실행 방지 코드 (Mutex)

Programming/C,CPP,CS 2018. 4. 18. 15:08 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

중복 실행 방지 코드 (Mutex)


CreateMutex function


Creates or opens a named or unnamed mutex object.

To specify an access mask for the object, use the CreateMutexEx function.

Syntax

HANDLE WINAPI CreateMutex(
  _In_opt_ LPSECURITY_ATTRIBUTES lpMutexAttributes,
  _In_     BOOL                  bInitialOwner,
  _In_opt_ LPCTSTR               lpName
);

Parameters

lpMutexAttributes [in, optional]

A pointer to a SECURITY_ATTRIBUTES structure. If this parameter is NULL, the handle cannot be inherited by child processes.

The lpSecurityDescriptor member of the structure specifies a security descriptor for the new mutex. If lpMutexAttributes is NULL, the mutex gets a default security descriptor. The ACLs in the default security descriptor for a mutex come from the primary or impersonation token of the creator. For more information, see Synchronization Object Security and Access Rights.

bInitialOwner [in]

If this value is TRUE and the caller created the mutex, the calling thread obtains initial ownership of the mutex object. Otherwise, the calling thread does not obtain ownership of the mutex. To determine if the caller created the mutex, see the Return Values section.

lpName [in, optional]

The name of the mutex object. The name is limited to MAX_PATH characters. Name comparison is case sensitive.

If lpName matches the name of an existing named mutex object, this function requests the MUTEX_ALL_ACCESSaccess right. In this case, the bInitialOwner parameter is ignored because it has already been set by the creating process. If the lpMutexAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored.

If lpName is NULL, the mutex object is created without a name.

If lpName matches the name of an existing event, semaphore, waitable timer, job, or file-mapping object, the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same namespace.

The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session namespace. The remainder of the name can contain any character except the backslash character (\). For more information, see Kernel Object Namespaces. Fast user switching is implemented using Terminal Services sessions. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can support multiple users.

The object can be created in a private namespace. For more information, see Object Namespaces.




#include <windows.h>
#include <stdio.h>

#define THREADCOUNT 2

HANDLE ghMutex; 

DWORD WINAPI WriteToDatabase( LPVOID );

int main( void )
{
    HANDLE aThread[THREADCOUNT];
    DWORD ThreadID;
    int i;

    // Create a mutex with no initial owner

    ghMutex = CreateMutex( 
        NULL,              // default security attributes
        FALSE,             // initially not owned
        NULL);             // unnamed mutex

    if (ghMutex == NULL) 
    {
        printf("CreateMutex error: %d\n", GetLastError());
        return 1;
    }

    // Create worker threads

    for( i=0; i < THREADCOUNT; i++ )
    {
        aThread[i] = CreateThread( 
                     NULL,       // default security attributes
                     0,          // default stack size
                     (LPTHREAD_START_ROUTINE) WriteToDatabase, 
                     NULL,       // no thread function arguments
                     0,          // default creation flags
                     &ThreadID); // receive thread identifier

        if( aThread[i] == NULL )
        {
            printf("CreateThread error: %d\n", GetLastError());
            return 1;
        }
    }

    // Wait for all threads to terminate

    WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);

    // Close thread and mutex handles

    for( i=0; i < THREADCOUNT; i++ )
        CloseHandle(aThread[i]);

    CloseHandle(ghMutex);

    return 0;
}

DWORD WINAPI WriteToDatabase( LPVOID lpParam )
{ 
    // lpParam not used in this example
    UNREFERENCED_PARAMETER(lpParam);

    DWORD dwCount=0, dwWaitResult; 

    // Request ownership of mutex.

    while( dwCount < 20 )
    { 
        dwWaitResult = WaitForSingleObject( 
            ghMutex,    // handle to mutex
            INFINITE);  // no time-out interval
 
        switch (dwWaitResult) 
        {
            // The thread got ownership of the mutex
            case WAIT_OBJECT_0: 
                __try { 
                    // TODO: Write to the database
                    printf("Thread %d writing to database...\n", 
                            GetCurrentThreadId());
                    dwCount++;
                } 

                __finally { 
                    // Release ownership of the mutex object
                    if (! ReleaseMutex(ghMutex)) 
                    { 
                        // Handle error.
                    } 
                } 
                break; 

            // The thread got ownership of an abandoned mutex
            // The database is in an indeterminate state
            case WAIT_ABANDONED: 
                return FALSE; 
        }
    }
    return TRUE; 
}



'Programming > C,CPP,CS' 카테고리의 다른 글

ActiveX 웹배포  (0) 2019.12.10
ffmpeg sample  (0) 2018.06.20
WAVE form wFormatTag IDs  (0) 2018.04.04
CString Tokenize  (0) 2017.10.19
[CPP] Windows Service 간단하게 만들기  (0) 2017.10.17

WAVE form wFormatTag IDs

Programming/C,CPP,CS 2018. 4. 4. 13:30 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

 

/* WAVE form wFormatTag IDs */

#define  WAVE_FORMAT_UNKNOWN                    0x0000 /* Microsoft Corporation */

#define  WAVE_FORMAT_ADPCM                      0x0002 /* Microsoft Corporation */

#define  WAVE_FORMAT_IEEE_FLOAT                 0x0003 /* Microsoft Corporation */

#define  WAVE_FORMAT_VSELP                      0x0004 /* Compaq Computer Corp. */

#define  WAVE_FORMAT_IBM_CVSD                   0x0005 /* IBM Corporation */

#define  WAVE_FORMAT_ALAW                       0x0006 /* Microsoft Corporation */

#define  WAVE_FORMAT_MULAW                      0x0007 /* Microsoft Corporation */

#define  WAVE_FORMAT_DTS                        0x0008 /* Microsoft Corporation */

#define  WAVE_FORMAT_DRM                        0x0009 /* Microsoft Corporation */

#define  WAVE_FORMAT_WMAVOICE9                  0x000A /* Microsoft Corporation */

#define  WAVE_FORMAT_WMAVOICE10                 0x000B /* Microsoft Corporation */

#define  WAVE_FORMAT_OKI_ADPCM                  0x0010 /* OKI */

#define  WAVE_FORMAT_DVI_ADPCM                  0x0011 /* Intel Corporation */

#define  WAVE_FORMAT_IMA_ADPCM                  (WAVE_FORMAT_DVI_ADPCM) /*  Intel Corporation */

#define  WAVE_FORMAT_MEDIASPACE_ADPCM           0x0012 /* Videologic */

#define  WAVE_FORMAT_SIERRA_ADPCM               0x0013 /* Sierra Semiconductor Corp */

#define  WAVE_FORMAT_G723_ADPCM                 0x0014 /* Antex Electronics Corporation */

#define  WAVE_FORMAT_DIGISTD                    0x0015 /* DSP Solutions, Inc. */

#define  WAVE_FORMAT_DIGIFIX                    0x0016 /* DSP Solutions, Inc. */

#define  WAVE_FORMAT_DIALOGIC_OKI_ADPCM         0x0017 /* Dialogic Corporation */

#define  WAVE_FORMAT_MEDIAVISION_ADPCM          0x0018 /* Media Vision, Inc. */

#define  WAVE_FORMAT_CU_CODEC                   0x0019 /* Hewlett-Packard Company */

#define  WAVE_FORMAT_YAMAHA_ADPCM               0x0020 /* Yamaha Corporation of America */

#define  WAVE_FORMAT_SONARC                     0x0021 /* Speech Compression */

#define  WAVE_FORMAT_DSPGROUP_TRUESPEECH        0x0022 /* DSP Group, Inc */

#define  WAVE_FORMAT_ECHOSC1                    0x0023 /* Echo Speech Corporation */

#define  WAVE_FORMAT_AUDIOFILE_AF36             0x0024 /* Virtual Music, Inc. */

#define  WAVE_FORMAT_APTX                       0x0025 /* Audio Processing Technology */

#define  WAVE_FORMAT_AUDIOFILE_AF10             0x0026 /* Virtual Music, Inc. */

#define  WAVE_FORMAT_PROSODY_1612               0x0027 /* Aculab plc */

#define  WAVE_FORMAT_LRC                        0x0028 /* Merging Technologies S.A. */

#define  WAVE_FORMAT_DOLBY_AC2                  0x0030 /* Dolby Laboratories */

#define  WAVE_FORMAT_GSM610                     0x0031 /* Microsoft Corporation */

#define  WAVE_FORMAT_MSNAUDIO                   0x0032 /* Microsoft Corporation */

#define  WAVE_FORMAT_ANTEX_ADPCME               0x0033 /* Antex Electronics Corporation */

#define  WAVE_FORMAT_CONTROL_RES_VQLPC          0x0034 /* Control Resources Limited */

#define  WAVE_FORMAT_DIGIREAL                   0x0035 /* DSP Solutions, Inc. */

#define  WAVE_FORMAT_DIGIADPCM                  0x0036 /* DSP Solutions, Inc. */

#define  WAVE_FORMAT_CONTROL_RES_CR10           0x0037 /* Control Resources Limited */

#define  WAVE_FORMAT_NMS_VBXADPCM               0x0038 /* Natural MicroSystems */

#define  WAVE_FORMAT_CS_IMAADPCM                0x0039 /* Crystal Semiconductor IMA ADPCM */

#define  WAVE_FORMAT_ECHOSC3                    0x003A /* Echo Speech Corporation */

#define  WAVE_FORMAT_ROCKWELL_ADPCM             0x003B /* Rockwell International */

#define  WAVE_FORMAT_ROCKWELL_DIGITALK          0x003C /* Rockwell International */

#define  WAVE_FORMAT_XEBEC                      0x003D /* Xebec Multimedia Solutions Limited */

#define  WAVE_FORMAT_G721_ADPCM                 0x0040 /* Antex Electronics Corporation */

#define  WAVE_FORMAT_G728_CELP                  0x0041 /* Antex Electronics Corporation */

#define  WAVE_FORMAT_MSG723                     0x0042 /* Microsoft Corporation */

#define  WAVE_FORMAT_MPEG                       0x0050 /* Microsoft Corporation */

#define  WAVE_FORMAT_RT24                       0x0052 /* InSoft, Inc. */

#define  WAVE_FORMAT_PAC                        0x0053 /* InSoft, Inc. */

#define  WAVE_FORMAT_MPEGLAYER3                 0x0055 /* ISO/MPEG Layer3 Format Tag */

#define  WAVE_FORMAT_LUCENT_G723                0x0059 /* Lucent Technologies */

#define  WAVE_FORMAT_CIRRUS                     0x0060 /* Cirrus Logic */

#define  WAVE_FORMAT_ESPCM                      0x0061 /* ESS Technology */

#define  WAVE_FORMAT_VOXWARE                    0x0062 /* Voxware Inc */

#define  WAVE_FORMAT_CANOPUS_ATRAC              0x0063 /* Canopus, co., Ltd. */

#define  WAVE_FORMAT_G726_ADPCM                 0x0064 /* APICOM */

#define  WAVE_FORMAT_G722_ADPCM                 0x0065 /* APICOM */

#define  WAVE_FORMAT_DSAT_DISPLAY               0x0067 /* Microsoft Corporation */

#define  WAVE_FORMAT_VOXWARE_BYTE_ALIGNED       0x0069 /* Voxware Inc */

#define  WAVE_FORMAT_VOXWARE_AC8                0x0070 /* Voxware Inc */

#define  WAVE_FORMAT_VOXWARE_AC10               0x0071 /* Voxware Inc */

#define  WAVE_FORMAT_VOXWARE_AC16               0x0072 /* Voxware Inc */

#define  WAVE_FORMAT_VOXWARE_AC20               0x0073 /* Voxware Inc */

#define  WAVE_FORMAT_VOXWARE_RT24               0x0074 /* Voxware Inc */

#define  WAVE_FORMAT_VOXWARE_RT29               0x0075 /* Voxware Inc */

#define  WAVE_FORMAT_VOXWARE_RT29HW             0x0076 /* Voxware Inc */

#define  WAVE_FORMAT_VOXWARE_VR12               0x0077 /* Voxware Inc */

#define  WAVE_FORMAT_VOXWARE_VR18               0x0078 /* Voxware Inc */

#define  WAVE_FORMAT_VOXWARE_TQ40               0x0079 /* Voxware Inc */

#define  WAVE_FORMAT_SOFTSOUND                  0x0080 /* Softsound, Ltd. */

#define  WAVE_FORMAT_VOXWARE_TQ60               0x0081 /* Voxware Inc */

#define  WAVE_FORMAT_MSRT24                     0x0082 /* Microsoft Corporation */

#define  WAVE_FORMAT_G729A                      0x0083 /* AT&T Labs, Inc. */

#define  WAVE_FORMAT_MVI_MVI2                   0x0084 /* Motion Pixels */

#define  WAVE_FORMAT_DF_G726                    0x0085 /* DataFusion Systems (Pty) (Ltd) */

#define  WAVE_FORMAT_DF_GSM610                  0x0086 /* DataFusion Systems (Pty) (Ltd) */

#define  WAVE_FORMAT_ISIAUDIO                   0x0088 /* Iterated Systems, Inc. */

#define  WAVE_FORMAT_ONLIVE                     0x0089 /* OnLive! Technologies, Inc. */

#define  WAVE_FORMAT_SBC24                      0x0091 /* Siemens Business Communications Sys */

#define  WAVE_FORMAT_DOLBY_AC3_SPDIF            0x0092 /* Sonic Foundry */

#define  WAVE_FORMAT_MEDIASONIC_G723            0x0093 /* MediaSonic */

#define  WAVE_FORMAT_PROSODY_8KBPS              0x0094 /* Aculab plc */

#define  WAVE_FORMAT_ZYXEL_ADPCM                0x0097 /* ZyXEL Communications, Inc. */

#define  WAVE_FORMAT_PHILIPS_LPCBB              0x0098 /* Philips Speech Processing */

#define  WAVE_FORMAT_PACKED                     0x0099 /* Studer Professional Audio AG */

#define  WAVE_FORMAT_MALDEN_PHONYTALK           0x00A0 /* Malden Electronics Ltd. */

#define  WAVE_FORMAT_RAW_AAC1                   0x00FF /* For Raw AAC, with format block AudioSpecificConfig() (as defined by MPEG-4), that follows WAVEFORMATEX */

#define  WAVE_FORMAT_RHETOREX_ADPCM             0x0100 /* Rhetorex Inc. */

#define  WAVE_FORMAT_IRAT                       0x0101 /* BeCubed Software Inc. */

#define  WAVE_FORMAT_VIVO_G723                  0x0111 /* Vivo Software */

#define  WAVE_FORMAT_VIVO_SIREN                 0x0112 /* Vivo Software */

#define  WAVE_FORMAT_DIGITAL_G723               0x0123 /* Digital Equipment Corporation */

#define  WAVE_FORMAT_SANYO_LD_ADPCM             0x0125 /* Sanyo Electric Co., Ltd. */

#define  WAVE_FORMAT_SIPROLAB_ACEPLNET          0x0130 /* Sipro Lab Telecom Inc. */

#define  WAVE_FORMAT_SIPROLAB_ACELP4800         0x0131 /* Sipro Lab Telecom Inc. */

#define  WAVE_FORMAT_SIPROLAB_ACELP8V3          0x0132 /* Sipro Lab Telecom Inc. */

#define  WAVE_FORMAT_SIPROLAB_G729              0x0133 /* Sipro Lab Telecom Inc. */

#define  WAVE_FORMAT_SIPROLAB_G729A             0x0134 /* Sipro Lab Telecom Inc. */

#define  WAVE_FORMAT_SIPROLAB_KELVIN            0x0135 /* Sipro Lab Telecom Inc. */

#define  WAVE_FORMAT_G726ADPCM                  0x0140 /* Dictaphone Corporation */

#define  WAVE_FORMAT_QUALCOMM_PUREVOICE         0x0150 /* Qualcomm, Inc. */

#define  WAVE_FORMAT_QUALCOMM_HALFRATE          0x0151 /* Qualcomm, Inc. */

#define  WAVE_FORMAT_TUBGSM                     0x0155 /* Ring Zero Systems, Inc. */

#define  WAVE_FORMAT_MSAUDIO1                   0x0160 /* Microsoft Corporation */

#define  WAVE_FORMAT_WMAUDIO2                   0x0161 /* Microsoft Corporation */

#define  WAVE_FORMAT_WMAUDIO3                   0x0162 /* Microsoft Corporation */

#define  WAVE_FORMAT_WMAUDIO_LOSSLESS           0x0163 /* Microsoft Corporation */

#define  WAVE_FORMAT_WMASPDIF                   0x0164 /* Microsoft Corporation */

#define  WAVE_FORMAT_UNISYS_NAP_ADPCM           0x0170 /* Unisys Corp. */

#define  WAVE_FORMAT_UNISYS_NAP_ULAW            0x0171 /* Unisys Corp. */

#define  WAVE_FORMAT_UNISYS_NAP_ALAW            0x0172 /* Unisys Corp. */

#define  WAVE_FORMAT_UNISYS_NAP_16K             0x0173 /* Unisys Corp. */

#define  WAVE_FORMAT_CREATIVE_ADPCM             0x0200 /* Creative Labs, Inc */

#define  WAVE_FORMAT_CREATIVE_FASTSPEECH8       0x0202 /* Creative Labs, Inc */

#define  WAVE_FORMAT_CREATIVE_FASTSPEECH10      0x0203 /* Creative Labs, Inc */

#define  WAVE_FORMAT_UHER_ADPCM                 0x0210 /* UHER informatic GmbH */

#define  WAVE_FORMAT_QUARTERDECK                0x0220 /* Quarterdeck Corporation */

#define  WAVE_FORMAT_ILINK_VC                   0x0230 /* I-link Worldwide */

#define  WAVE_FORMAT_RAW_SPORT                  0x0240 /* Aureal Semiconductor */

#define  WAVE_FORMAT_ESST_AC3                   0x0241 /* ESS Technology, Inc. */

#define  WAVE_FORMAT_GENERIC_PASSTHRU           0x0249

#define  WAVE_FORMAT_IPI_HSX                    0x0250 /* Interactive Products, Inc. */

#define  WAVE_FORMAT_IPI_RPELP                  0x0251 /* Interactive Products, Inc. */

#define  WAVE_FORMAT_CS2                        0x0260 /* Consistent Software */

#define  WAVE_FORMAT_SONY_SCX                   0x0270 /* Sony Corp. */

#define  WAVE_FORMAT_FM_TOWNS_SND               0x0300 /* Fujitsu Corp. */

#define  WAVE_FORMAT_BTV_DIGITAL                0x0400 /* Brooktree Corporation */

#define  WAVE_FORMAT_QDESIGN_MUSIC              0x0450 /* QDesign Corporation */

#define  WAVE_FORMAT_VME_VMPCM                  0x0680 /* AT&T Labs, Inc. */

#define  WAVE_FORMAT_TPC                        0x0681 /* AT&T Labs, Inc. */

#define  WAVE_FORMAT_OLIGSM                     0x1000 /* Ing C. Olivetti & C., S.p.A. */

#define  WAVE_FORMAT_OLIADPCM                   0x1001 /* Ing C. Olivetti & C., S.p.A. */

#define  WAVE_FORMAT_OLICELP                    0x1002 /* Ing C. Olivetti & C., S.p.A. */

#define  WAVE_FORMAT_OLISBC                     0x1003 /* Ing C. Olivetti & C., S.p.A. */

#define  WAVE_FORMAT_OLIOPR                     0x1004 /* Ing C. Olivetti & C., S.p.A. */

#define  WAVE_FORMAT_LH_CODEC                   0x1100 /* Lernout & Hauspie */

#define  WAVE_FORMAT_NORRIS                     0x1400 /* Norris Communications, Inc. */

#define  WAVE_FORMAT_SOUNDSPACE_MUSICOMPRESS    0x1500 /* AT&T Labs, Inc. */

#define  WAVE_FORMAT_MPEG_ADTS_AAC              0x1600 /* Microsoft Corporation */

#define  WAVE_FORMAT_MPEG_RAW_AAC               0x1601 /* Microsoft Corporation */

#define  WAVE_FORMAT_MPEG_LOAS                  0x1602 /* Microsoft Corporation (MPEG-4 Audio Transport Streams (LOAS/LATM) */

#define  WAVE_FORMAT_NOKIA_MPEG_ADTS_AAC        0x1608 /* Microsoft Corporation */

#define  WAVE_FORMAT_NOKIA_MPEG_RAW_AAC         0x1609 /* Microsoft Corporation */

#define  WAVE_FORMAT_VODAFONE_MPEG_ADTS_AAC     0x160A /* Microsoft Corporation */

#define  WAVE_FORMAT_VODAFONE_MPEG_RAW_AAC      0x160B /* Microsoft Corporation */

#define  WAVE_FORMAT_MPEG_HEAAC                 0x1610 /* Microsoft Corporation (MPEG-2 AAC or MPEG-4 HE-AAC v1/v2 streams with any payload (ADTS, ADIF, LOAS/LATM, RAW). Format block includes MP4 AudioSpecificConfig() -- see HEAACWAVEFORMAT below */

#define  WAVE_FORMAT_DVM                        0x2000 /* FAST Multimedia AG */

#define  WAVE_FORMAT_DTS2                       0x2001

 

 


'Programming > C,CPP,CS' 카테고리의 다른 글

ffmpeg sample  (0) 2018.06.20
중복 실행 방지 코드 (Mutex)  (0) 2018.04.18
CString Tokenize  (0) 2017.10.19
[CPP] Windows Service 간단하게 만들기  (0) 2017.10.17
WaitForMultipleObjects  (0) 2017.04.19

Android Camera 권한

Programming/Android 2018. 3. 6. 20:08 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Android Camera 권한


Android M 이후 버전에서는 


팝업으로 사용자에게 권한을 받아한다.



/**********권한 요청************/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
/**
* 사용자 단말기의 권한 중 "카메라" 권한이 허용되어 있는지 확인한다.
* Android는 C언어 기반으로 만들어졌기 때문에 Boolean 타입보다 Int 타입을 사용한다.
*/
int permissionResult = checkSelfPermission(Manifest.permission.CAMERA);


/** * 패키지는 안드로이드 어플리케이션의 아이디이다. *
* 현재 어플리케이션이 카메라에 대해 거부되어있는지 확인한다. */
if (permissionResult == PackageManager.PERMISSION_DENIED) {


/** * 사용자가 CALL_PHONE 권한을 거부한 적이 있는지 확인한다. *
* 거부한적이 있으면 True를 리턴하고 *
* 거부한적이 없으면 False를 리턴한다. */
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("권한이 필요합니다.").setMessage("이 기능을 사용하기 위해서는 단말기의 \"카메라\" 권한이 필요합니다. 계속 하시겠습니까?")
.setPositiveButton("네", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

/** * 새로운 인스턴스(onClickListener)를 생성했기 때문에 *
* 버전체크를 다시 해준다. */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// CALL_PHONE 권한을 Android OS에 요청한다.
requestPermissions(new String[]{Manifest.permission.CAMERA}, 1000);
}
}
})
.setNegativeButton("아니요", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "기능을 취소했습니다", Toast.LENGTH_SHORT).show();
}
}).create().show();


return -1;
// need to retry
}
// 최초로 권한을 요청할 때
else {
// CALL_PHONE 권한을 Android OS에 요청한다.
requestPermissions(new String[]{Manifest.permission.CAMERA}, 1000);
}
}
// CALL_PHONE의 권한이 있을 때
else {
}
}
/************권한요청 끝**************/






JNA Error

Programming/JAVA,JSP 2018. 2. 27. 15:48 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

JNA Error













int hr = m_pObjectKey.CreateInstance(__uuidof(KeyObject));


해당 구문에서


CreateInstance 의 리턴 값이



%x : 80040154


%d : -2147221164


형태로 계속 리턴되는 경우








80040154 오류
















System.Runtime.InteropServices.COMExcetption : 80040154 오류로 인해 CLSID가 {100202C1-E260-11CF-AE68-00AA004A34D5}인 구성 요소의 COM 클래스 팩터리를 검색하지 못했습니다.


https://social.msdn.microsoft.com/Forums/vstudio/ko-KR/03d5a6bd-e256-492a-a72b-f011b971834e/80040154-?forum=visualcsharpko
















쉽게 말하면 해당 라이브러리의 DLL 파일의 경로를 찾을수 없어서


객체를 만들 수 없다는 이야기이다.



















1) regasm, regsrv 를 이용하여 재등록을 시도해 보고,







그래도 안된다면









2) regasm 의 경우 /codebase 옵션을 사용 해 보라






























C# 에서 C++ DLL 불러서 쓰기 #5

Programming/C# 2018. 2. 15. 17:31 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


C# 에서 C++ DLL 불러서 쓰기 #5














5. error CS0214: 포인터와 고정 크기 버퍼는 안전하지 않은 컨텍스트에서만 사용할 수 있습니다.




포인터와 고정 크기 버퍼는 안전하지 않은 컨텍스트에서만 사용할 수 있습니다.

포인터는 안전하지 않은 키워드에만 사용할 수 있습니다. 자세한 내용은 안전하지 않은 코드 및 포인터를 참조하세요.

다음 샘플에서는 CS0214를 생성합니다.




// CS0214.cs  

// compile with: /target:library /unsafe  

public struct S  

{  

   public int a;  

}  


public class MyClass  

{  

   public static void Test()  

   {  

      S s = new S();  

      S * s2 = &s;    // CS0214  

      s2->a = 3;      // CS0214  

      s.a = 0;  

   }  


   // OK  

   unsafe public static void Test2()  

   {  

      S s = new S();  

      S * s2 = &s;  

      s2->a = 3;  

      s.a = 0;  

   }  

}  






unsafe 키워드를 붙여주면 된다.








C# 에서 C++ DLL 불러서 쓰기 #4

Programming/C# 2018. 2. 14. 12:30 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

C# 에서 C++ DLL 불러서 쓰기 #4



4. 멤버 함수 가져오기





C++


#ifdef BOX_EXPORTS

#define BOX_API __declspec(dllexport)

#else

#define BOX_API __declspec(dllimport)

#endif






Class BOX_API Box{

public:

Box();

int setInt(int a);

void setString(char* str);

}






int setInt(int a);

void setString(char* str);




이 멤버 함수들을 가져와서 사용하고 싶다.



참고 : http://tansanc.tistory.com/526?category=772232 [TanSanC]





아래와 같이 사용하고 싶지만


불가능하다



namespace BoxConsoleApplication

{

    class Program

    {


        [DllImport("Box.dll", CallingConvention = CallingConvention.Cdecl)]

        static public extern IntPtr CreateCBox();

        

        

        [DllImport("Box.dll", CallingConvention = CallingConvention.Cdecl)]

        static public extern void DisposeCBox(IntPtr pTestClassObject);


        unsafe static void Main(string[] args)

        {


            IntPtr pCBoxClass = CreateCBox(); ;



            pCBoxClass.setInt(3);

            pCBoxClass.setString("HelloWorld");




            DisposeCBox(pCBoxClass );            




            pCBoxClass = IntPtr.Zero; 


        }

    }

}





            pCBoxClass.setInt(3);

            pCBoxClass.setString("HelloWorld");




클래스 내부 멤버 변수라 바로 가져올 수는 없다.






사용 할 수 있는 방법은


클래스 생성시와 같이


extern 으로 접근가능 하도록 만들어 주어야 한다.











기본 형태





C++






.h


extern "C" BOX_API int setInt(CBox* pObject, int a);






.cpp


extern "C" BOX_API int setInt(CBox* pObject, int a)

{

if (pObject != NULL)

{

pObject->setInt(a);

}

return -1;

}





이렇게 C++ DLL 내부에서 


클래스 객체에 접근하여


객체의 멤버 함수를 호출하여 준다.











void setString(char* str);



는 다음 글에서....






336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

C# 에서 C++ DLL 불러서 쓰기


도움되는 링크들





http://freeprog.tistory.com/220




https://docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/keywords/unsafe



http://heroeskdw.tistory.com/entry/C-MFC-DLL%EC%9D%84-C%EC%97%90%EC%84%9C-%EB%A1%9C%EB%94%A9%ED%95%98%EA%B8%B0


https://www.codeproject.com/Articles/18032/How-to-Marshal-a-C-Class




http://www.sysnet.pe.kr/2/0/11132







http://www.sysnet.pe.kr/2/0/11111







https://msdn.microsoft.com/ko-kr/library/62688esh.aspx












https://social.msdn.microsoft.com/Forums/en-US/b85fc9dd-acc5-42dc-a28e-b70953bf1170/unhandled-exception-systemruntimeinteropservicessehexception-additional-information-external?forum=vcgeneral

















https://msdn.microsoft.com/ko-kr/library/system.io.filestream.read(v=vs.110).aspx







http://storycompiler.tistory.com/214






























C# 에서 C++ DLL 불러서 쓰기 #2

Programming/C# 2018. 2. 13. 15:55 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

C# 에서 C++ DLL 불러서 쓰기 #2



2. DLL 참조하기




C++ DLL 을 C# 에서 사용하려면


일단 참조를 하여야 한다.




참조를 하는 방법은




Visual Studio 2013 버전에서는






[솔루션 탐색기] -> [솔루션] 하위 -> [프로젝트] 하위 -> [참조] -> 우클릭 -> [참조 추가] -> 우측 하단 [찾아보기(B)...] -> 원하는 DLL 찾아서 선택



선택을 하면 [참조] 하단에 참조된 DLL 이 보이게 된다.










여기서.......



이 글은


참조된 DLL 을 더블클릭하여 [개체 브라우저]로 보았을때도


하위 멤버들이 보이지 않는


C++ DLL 일 경우 해결하는 방법들을


순서...에 상관없이


메모해 두려고 한다.









C# 에서 C++ DLL 불러서 쓰기 #3

Programming/C# 2018. 2. 13. 15:49 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

C# 에서 C++ DLL 불러서 쓰기 #3















3. Class 가져오기



C++ DLL 에



#ifdef BOX_EXPORTS

#define BOX_API __declspec(dllexport)

#else

#define BOX_API __declspec(dllimport)

#endif











C++


Class BOX_API Box{

public:

Box();

int setInt(int a);

void setString(char* str);

}








이런 클래스가 존재하고






C# 에서 해당 클래스를 불러서 사용하려고 한다,









C#



namespace BoxConsoleApplication

{

    class Program

    {


        unsafe static void Main(string[] args)

        {

             Box b = new Box();

             int c = b.setInt(3);

             b.setString("HelloWorld");


        }

    }

}



이렇게 사용하고 싶다.












하지만 바로 저렇게 사용 할 수는 없다.






참조하여도 해당 멤버들이 [개체브라우저]에 보이지 않는 멤버들을 직접 명시하여 참조해 주어야한다.











C++ 클래스가 보이지 않으므로


C++ 클래스를 활용 할 수 있는 전역 함수들을 만들어서


명시하여 C# 에서 사용한다.



C++


Class BOX_API CBox{

public:

CBox();

int setInt(int a);

void setString(char* str);

}






.h File


extern "C" BOX_API Box* CreateCBox();

extern "C" BOX_API void DisposeCBox(CBox* pObject);







.c File


extern "C" BOX_API CBox* CreateCBox()

{

return new CBox();

}


extern "C" BOX_API void DisposeCBox(CBox* pObject)

{

if (pObject != NULL)

{

delete pObject;

pObject = NULL;

}

}




CBox 객체를 만들고 해당 객체를 반환하고,


CBox 를 받아서 해당 객체를 지워주는 함수 2개를 일단 생성한다.




함수 원형과 함수 구현을 .c , .h 파일로 나누어 두었는데,


.h 에 모두 구현하게 되면


.h(104): error C2491: 'CreateCBox' : dllimport 함수을(를) 정의할 수 없습니다.


라는 에러를 보게 될 것이다.







만들어진 C++ 의 Create, Dispose 함수를 C# 에서 사용 해 본다.









C#



namespace BoxConsoleApplication

{

    class Program

    {


        [DllImport("Box.dll", CallingConvention = CallingConvention.Cdecl)]

        static public extern IntPtr CreateCBox();

        

        

        [DllImport("Box.dll", CallingConvention = CallingConvention.Cdecl)]

        static public extern void DisposeCBox(IntPtr pTestClassObject);


        unsafe static void Main(string[] args)

        {


            IntPtr pCBoxClass = CreateCBox(); ;


            DisposeCBox(pCBoxClass );            


            pCBoxClass = IntPtr.Zero; 


        }

    }

}







이렇게 하면


C++ DLL 의


클래스가


만들어진다.





나머지 멤버 함수들을 가져오는 것은 다음에 정리한다.










C# 에서 C++ DLL 불러서 쓰기 #1

Programming/C# 2018. 2. 13. 15:39 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

C# 에서 C++ DLL 불러서 쓰기 #1



1. DllImport






DLL Import 시






        [DllImport("CPPDLL.dll"] ,  


         혹은 


        [DllImport("CPPDLL.dll", CallingConvention = CallingConvention.Cdecl)]



         쓰는 것을 볼 수 있다.






C#의 DllImport 특성은 기본 CallingConvention이 StdCall로 되어 있습니다.









DllImportAttribute Class

; https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute(v=vs.110).aspx


DllImportAttribute.CallingConvention Field

; https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.callingconvention(v=vs.110).aspx












일반적인 코드는 __cdecl, __stdcall에 상관없이 C#에서는 명시적인 CallingConvention 없이도 잘 실행됩니다.












하지만 .Net 4.0 이상의 빌드 환경에서는 


명시적인 CallingConvention 이 필요할 수 있습니다.


















.Net 4.0 이상에서는


        [DllImport("CPPDLL.dll", CallingConvention = CallingConvention.Cdecl)]


이 방법으로 사용하는 것을 추천합니다.


































참고 : http://www.sysnet.pe.kr/2/0/11132 [C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (1) - x86 환경에서의 __cdecl, __stdcall에 대한 Name mangling]